Search notes:

Python: List

A list is a sequence type. It can contain objects of different types which also makes it a container.
In order to create a list of elements that all have the same types, the array module can be used.
A list is not a linked list, it provides access to its element in O(1).

Members of list

append(x) Adds x at the list's end. Equivalent to a[len(a):] = x.
clear() Remove all eleemnts from the list. Equivalent to del a[:]
copy() Returns a shallow copy, equivalent to a[:]
count(v) Counts the elements with a given value (v).
extend()
index()
insert()
pop() Removes the last element from the list, or the element at the position given with the optional parameter.
remove(x) Removes the first element equal to x (or throws ValueError)
reverse() Reverses the order of the elements in place (i. e. returns None). In order to return a reversed copy of the list, use lst[::-1].
sort() Sorts the list in place. Compare with the sorted() function.

Creating a list from a string

When a list is created from a string, the characters of the string become the elements in the list:
t = list('hello')

print(t)
#
#  ['h', 'e', 'l', 'l', 'o']
Github repository about-Python, path: /types/list/create-from-string.py
The same is also the case for tuples.

Removing elements from a list

An element whose value is known can be removed with remove(val):
lst = [ 'foo', 'bar', 'xyz', 'baz' ]
lst.remove('xyz')
print(lst)
#
#  ['foo', 'bar', 'baz']
Github repository about-Python, path: /types/list/remove.py
An element whose index is known can be removed from a list with del(lst[ix]).
The last element of a list can be removed with pop()
lst.clear() removes all elements from lst. It is equivalent to del lst[:].

Slicing a list

A list can be sliced to return a «region» of a list. Optionally, every nth element from this region can be extrected. The notation is:
lst[start:]
lst[:stop]
lst[start:stop]
lst[start:stop:step]
lst[:]                 # Create a copy of the list
Note that the element that is indicated with stop is not returned.
Negative numbers count from the end of the list.
lst = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six' ]

print( lst[4:] )
#
# ['four', 'five', 'six']

print( lst[:4] )
#
# ['zero', 'one', 'two', 'three']

print( lst[1:6] )
#
# ['one', 'two', 'three', 'four', 'five']

print( lst[1:-1] )
#
# ['one', 'two', 'three', 'four', 'five']

print( lst[1:-1:2] )
#
# ['one', 'three', 'five']

print( lst[:] )
#
# ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
Github repository about-Python, path: /types/list/slicing.py
Slicing can be used to return a copy of the list with its elements reversed (compare to the reverse() method that reverses the elements in place and reversing a string):
lst = [0,1,2,3,4,5]
tsl = lst[::-1]     # tsl = [5,4,3,2,1,0]
See also the built-in function slice()

pop(): remove elements from the end of the list

last_elem = lst.pop() removes the last element of a list and returns it.
pop(n) removes the n-th element and returns it.
If n is negative, it removes the n-th last element from the list.
L = ['one', 'two', 'three', 'four', 'five']

p = L.pop()

print (p)
# five

print (L)
# ['one', 'two', 'three', 'four']

p = L.pop(2)
print (p)
# three

print (L)
# ['one', 'two', 'four']
Github repository about-python, path: /types/list/pop.py
Note that performance is not ideal if elements are popped from the beginning because the entire list needs then to be shifted. In order to implement FIFO-queues, collections.deque should be used.

Inserting elements

L = ['one', 'two', 'three', 'five']

L.insert(3, 'four')

print (L)
# ['one', 'two', 'three', 'four', 'five']
Github repository about-python, path: /types/list/insert.py

Counting elements with a given value

lst.count(val) counts how many times val occurs in lst:
L = ['three', 'one', 'two', 'three', 'two', 'three']

print L.count('one')
# 1

print L.count('three')
# 3
Github repository about-python, path: /types/list/count.py

Getting the position of a given value

lst.index(val) gets the first position of val in lst.
lst.index(val, pos) gets the first position of val in lst starting as position pos.
If val is not found, index() raises a ValueError exception.
items = [ 'foo', 'baz', 'foo', 'bar', 'foo', 'baz', 'baz', 'bar', 'foo', 'baz' ]

try:

  ix = 0
  while True:
    ix = items.index('foo', ix)
    print(f'found foo at position {ix}')
    ix += 1

except ValueError:
   pass
Github repository about-python, path: /types/list/index.py

Adding and multiplying lists

The list type defines the mathematical operations + and *. The plus operator creates a new list that contains the elements of the two lists being added. The multiplication operator creates a new list that contains the elements of a list repeated n times:
lst_1 = ['one' , 'two' , 'three']
lst_2 = ['four', 'five'         ]

print(lst_1 + lst_2)
#
#  ['one', 'two', 'three', 'four', 'five']

print(3 * lst_2)
#
#  ['four', 'five', 'four', 'five', 'four', 'five']
Github repository about-python, path: /types/list/add-mult.py
A pairwise addition or multiplication is possible with the zip() function together with a list comprehension:
lst_1 = [3, 7, 5]
lst_2 = [4, 2, 1]

lst_a = [ x+y for x, y in zip(lst_1, lst_2) ]
lst_m = [ x*y for x, y in zip(lst_1, lst_2) ]

print(lst_a)
#
#  [7, 9, 6]

print(lst_m)
#
#  [12, 14, 5]
Github repository about-python, path: /types/list/pairwise-add-mult.py

Starred expressions

An asterisk before a list expands («explodes») the list into its context (see also iterable unpacking):
>>> a = [1,2,3]
>>> [0, a, 4]
[0, [1, 2, 3], 4]
>>> [0, *a, 4]
[0, 1, 2, 3, 4]
>>> b = [1,2,3]
>>> *b
…
SyntaxError: can't use starred expression here

Beware of += string

Note, because a string is an iterable, list += 'text' adds each character of a string to a list which might be surprising when first seen:
words  = ['one' , 'two' , 'three']
words +=  'four'

print(words)
#
#  ['one', 'two', 'three', 'f', 'o', 'u', 'r']
Github repository about-python, path: /types/list/beware-of-plus-equal-string.py
Of course, a single string should be added to the list with lst.append('four').

See also

The list built in function
list.sort()
for … in …
Selecting a random element from a list with random.choice(lst)
The list() built-in function
list comprehension allows to create another list by applying an expression on each element in the list.
Comparing lists with tuples.
The collections module.
collections.deque is a list-like object that is able to add and remove elements from both ends fast.
Other Built-in types

Index