1. list

  • Can store elements of any types

  • Mutable - can add, remove, and modify items

  • Brackets are required

  • Comma after last element is optional

1.1. Defining list

  • list() is more readable

  • [] is used more often

1.1.1. Empty list

my_list = []
my_list = list()

1.1.2. One element list

my_list = [1]
my_list = [1,]

1.1.3. Many element list

my_list = [1, 2.0, None, False, 'José']
alphabet = list('ABCDE')
# ['A', 'B', 'C', 'D', 'E']

1.2. Adding elements

1.2.1. list arithmetic

my_list = [1, 2]

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

1.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]]

1.2.3. Extending lists

my_list = [1, 2]

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

1.2.4. Inserting elements at specific position

my_list = [1, 2]

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

1.3. sorted() vs. list.sort()

1.3.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]

1.3.2. list.sort()

  • list.sort() zmienia listę na stałe

numbers = [3, 1, 2]

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

1.4. Multiple statements in one line

my_list = [3, 1, 2]

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

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

1.5. Built-in functions on sequences

1.5.1. len()

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

len(numbers)        # 5

1.5.2. min()

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

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

1.5.3. max()

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

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

1.5.4. sum()

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

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

1.6. Membership Operators

Tab. 1.5. 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

1.7. Length of a list

my_list = [1, 2, 3]

len(my_list)    # 3