6. list

  • Can store elements of any types
  • Mutable - can add, remove, and modify items
  • Brackets are required
  • Comma after last element is optional

6.1. Defining list

  • list() is more readable
  • [] is used more often

6.1.1. Empty list

my_list = []
my_list = list()

6.1.2. One element list

my_list = [1]
my_list = [1,]

6.1.3. Many element list

my_list = [1, 2.0, None, False, 'José']

6.1.4. Nested list

my_list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
my_list = [1, 2.0, [1, 'hello'], None, [2, 1]]

6.2. Adding elements

6.2.1. list arithmetic

my_list = [1, 2]

my_list + [3, 4]        # [1, 2, 3, 4]

6.2.2. Appending elements

my_list = [1, 2]

my_list.append(3)       # [1, 2, 3]
my_list.append([4, 5])  # [1, 2, 3, [4, 5]]

6.2.3. Extending lists

my_list = [1, 2]

my_list.extend([3, 4])  # [1, 2, 3, 4]

6.2.4. Inserting elements at specific position

my_list = [1, 2]

my_list.insert(0, 'a')  # ['a', 1, 2]

6.2.5. Multiple statements in one line

my_list = [3, 1, 2]

a = my_list.append(4).sort()
# AttributeError: 'NoneType' object has no attribute 'sort'

6.3. Slicing list

  • Slicing works the same as for str
  • More in Slicing chapter
my_list = [1, 2.0, None, False, 'José']

my_list[1]             # 2.0
my_list[2:4]           # [None, False]
my_list[::2]           # [1, None, 'José']
my_list[-1]            # 'José'

6.4. sorted() vs. list.sort()

6.4.1. sorted()

  • sorted() zwraca posortowaną listę, ale nie zapisuje zmienionej kolejności
numbers = [3, 1, 2]

sorted(numbers)     # returns [1, 2, 3]
print(numbers)      # [3, 1, 2]

6.4.2. list.sort()

  • list.sort() zmienia listę na stałe
numbers = [3, 1, 2]

numbers.sort()      # returns None
print(numbers)      # [1, 2, 3]

6.5. Built-in functions on sequences

6.5.1. len()

numbers = [1, 2, 3, 4, 5]

len(numbers)                   # 5
len('Max')                     # 3

6.5.2. min()

numbers = [1, 2, 3, 4, 5]

min(numbers)  # 1
min(3, 1, 5)  # 1

6.5.3. max()

numbers = [1, 2, 3, 4, 5]

max(numbers)  # 5
max(3, 1, 5)  # 5

6.5.4. sum()

numbers = [1, 2, 3, 4, 5]

sum(numbers)  # 15
sum(3, 1, 5)  # 9

6.6. Membership Operators

Tab. 6.1. Membership operators
Operand Example Description
x == y x == 18 value of x is equal to y
x != y x != 18 value of x is not equal to y
x in y x in [1, 2, 3] x contains y
x not in y x not in [1, 2, 3] x not contains y

6.7. Length of a list

my_list = [1, 2, 3]

len(my_list)    # 3