Search notes:
Python: List
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']
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']
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']
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]
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']
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']
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
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
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']
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]
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']
Of course, a single string should be added to the list with lst.append('four')
.
See also
The
list
built in function
list comprehension allows to create another list by applying an expression on each element in the list.