Skip to content

Lists

An ordered collection of items. The concept of lists is similar to the concept of arrays in other languages but with more extensive functionalities.

Defining a List

int_list = [10, 20, 30]
mixed_list = [10, "Hello", 20.30]
list_of_lists = [int_list, mixed_list, []]

Accessing a List

lst = [0, 1, 2, 3, 4]
one = lst[0]
one
0
four = lst[-1]
four
4
three = lst[-2]
three
3

Slicing a List

lst[0:-1]
[0, 1, 2, 3]
lst[:3]
[0, 1, 2]
lst[1:]
[1, 2, 3, 4]
lst[:] # Copy
[0, 1, 2, 3, 4]
lst[::2] # Every second element
[0, 2, 4]
lst[4:0:-1]
[4, 3, 2, 1]

Extending a List

lst + [5,6,7]
[1, 2, 3, 4, 5, 6, 7]
lst
[1, 2, 3, 4]
lst.extend([5,6,7])
lst
[1, 2, 3, 4, 5, 6, 7]

Unpack a List

lst = [1,2]
x, y = lst
print(x, " ", y)
1   2

_, y = lst
y
2