Python Language List

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

A list is a mutable sequence type that contains zero or more elements and whose elements can be of the same type or different types. The elements of a list are ordered. As mentioned, the list is mutable, in that a list can be changed in-place, new elements can be added to it, and existing elements can be overwritten. Unlike a set, a list can contain the same element multiple times, a list element does not need to be unique in the list.

List type()

The function type() applied to a list returns: <class 'list'>

To check whether an instance is a list:

i = ...
if type(i) is list:
  ...

For list subclasses:

i = ...
if isinstance(i, list):
  ...

Create a List

A list can be created with the [] syntax, with the list() functions and with list comprehensions.

Create a List with []

A list can be created specifying the list elements, separate them by comma and enclose them in square brackets.

empty_list = []
some_list = ['A', 'B', 'C']
some_other_list = ['A', 2, 3.0, ['B', 4]]

Create a List or Convert other Data Type to a List with list()

An empty list can be created with the list() function:

empty_list = list()

The list() function converts the data types to lists. list() applied to a list creates a copy of that list. The data types that can be converted are:

String to List

s = 'abc'
l = list(s)
assert l == ['a', 'b', 'c']

Tuple to List

t = ('a', 'b', 'c')
l = list(t)
assert l == ['a' ,'b', 'c']

Create a Copy of a List

l = ['a', 'b', 'c']
l2 = l.copy()

l[0] = 'x'
assert 'x' == l[0]
assert 'a' == l2[0]

Access a List

Test for Empty List

Test for Existence of an Element in List

A Python idiomatic way to test whether a value is in the list is using in:

l = ['a', 'b', 'c', 'b', 'd']
if 'a' in l:
  print("'a' found")
else:
  print("'a' NOT found")
if 'x' in l:
  print("'x' found")
else:
  print("'x' NOT found")

The offset of an element with a certain value can be returned by calling index().

l = ['a', 'b', 'c', 'b', 'd']
assert 1 == l.index('b')

If the element exists in list, the index() returns the offset of the first value in the list, in case the value exists more than once. If the value does not exist, the method will throw ValueError: '...' is not in list.

Access an Element in List

The element of a list can be accessed using the [<offset>] syntax. The offset is zero-based, and it can be positive or negative.

l = ['a', 'b', 'c']
print(l[0])

Negative indices count backward from the end, the last element is identified with a -1 index. Think about it as index = len(list) - negative-index.

l = ['a', 'b', 'c']
assert 'c' == l[-1]
assert 'b' == l[-2]

⚠️ In case of both positive and negative indices, the offset should be valid. If the indices fall outside of the list's bounds, IndexError: list index out of range exception is thrown.

Length of a List

The number of elements is given by the len() function:

l = ['a', 'b', 'c']
assert 3 == len(l)

Count Occurrences of a Value with count()

l = ['a', 'b', 'c', 'a']
assert 2 == l.count('a')

Iterate over a List

l = ['A', 'B', 'C']
for i, e in enumerate(l):
    print(f'index: {i}, element: {e}')

Slices

A sub-sequence of a list can be extracted with a slice. The slice [<start-index>:<end-index>:<step>] specified the index of the last element, and the index of the first element not included in slice, and the step. The step is optional, the default value is 1.

l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['a', 'b', 'c', 'd', 'e', 'f'] == l[:] # starts from the beginning and ends after the end of the list
assert ['c', 'd'] == l[2:4]
assert ['c'] == l[2:4:2]

The step can be negative, which means the slice starts at the end and goes from right to left.

l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['f', 'e', 'd', 'c', 'b', 'a'] == l[::-1]

[:] creates a copy of the list.

l = ['a', 'b', 'c']
l2 = l[:]
l2[0] = 'x'
assert ['a', 'b', 'c'] == l
assert ['x', 'b', 'c'] == l2

Remove the last element of the list:

l = ['a', 'b', 'c']
l2 = l[:-1]
assert ['a', 'b'] == l2

Modify a List

Modify Individual Elements

Modify an Element Identified by [offset]

An element of a list can be modified using the [<offset>] syntax. The offset is zero-based, and it can be positive or negative, as described in Access an Element in List.

l = ['a', 'b', 'c']
l[1] = 'd'
print(l[1])

Append an Element

The traditional way of adding items to a list is to append() them one by one to the end of the list. The invocation increases the length of the list.

l = [1, 2, 3]
l.append(10)
print(l) # will display [1, 2, 3, 10]

append() adds the argument to the end of the list, as one element, even if it's another list. To extend the list by adding the elements individually, use extend() or +=.

Append a List

A list can be extended with another list with the extend() function:

l1 = [1, 2, 3]
l2 = [10, 20]
l1.extend(l2)
print(l1) # will display [1, 2, 3, 10, 20]

The extend() function is equivalent with the += operator:

l1 = [1, 2, 3]
l2 = [10, 20]
l1 += l2
print(l1) # will display [1, 2, 3, 10, 20]

Insert an Element in the Middle of a List

insert(offset, element) inserts an element in the middle of the list. For a 0 offset, the function will insert the element at the beginning of the list. If the offset falls outside the list boundaries, it will add at the end of the list without throwing an exception. When an item is deleted from a list, the items that follow it shift left to take its position and the length of the list decreases by one.

l1 = [1, 2, 3]
l1.insert(1, 10)
print(l1) # will display [1, 10, 2, 3]
l1.insert(1000, 20)
print(l1) # will display [1, 10, 2, 3, 20]
l1.insert(-1000, 40)
print(l1) # will display [40, 1, 10, 2, 3, 20]

Delete an Element by Offset

To delete an element by offset use del list_name[<offset>]. The offset can be positive or negative. Using -1 deletes the last element from the list.

l = [1, 2, 3]
del l[0] # the list is now [2, 3]
del l[-1] # the list is now [2]

Delete an Element by its Value

remove() deletes an element from a list based on its value. If more than one elements have the same value, only the first one is removed.

Return and Remove an Element with pop()

An element identified by offset can be returned and deleted from the list. Positives and negative offsets work.

l = [1, 2, 3]
print(l.pop(1)) # displays 2
print(l) # displays [1, 3]

pop() without argument implies -1: the last element of the list will be returned and deleted.

Delete All Elements

Copy a List

Multi-Dimensional Lists

m = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
print(m[2][1]) # prints 8