1. list

  • Can store elements of any types

  • Mutable - can add, remove, and modify items

1.1. Initializing

  • list() is more readable

  • [] is used more often

1.1.1. Initialize empty

my_list = []
my_list = list()

1.1.2. Initialize with one element

  • Comma after last element is optional

  • Brackets are required

my_list = [1]
my_list = [1,]

1.1.3. Initialize with many elements

  • Brackets are required

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

1.2. Adding elements

1.2.1. Appending elements

my_list = [1, 2]

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

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

1.2.2. Extending lists

my_list = [1, 2]

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

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

1.2.3. Inserting elements at specific position

my_list = [1, 2]

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

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

1.3. Accessing elements

my_list = ['a', 'b', 'c', 'd']

my_list[0]         # 'a'
my_list[1]         # 'b'
my_list[3]         # 'd'
my_list = ['a', 'b', 'c', 'd']

my_list[-1]        # 'd'
my_list[-3]        # 'b'

1.4. sorted() vs. list.sort()

1.4.1. sorted()

  • sorted() zwraca posortowaną listę, ale nie zapisuje zmienionej kolejności

numbers = [3, 1, 2]

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

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

1.4.2. list.sort()

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

numbers = [3, 1, 2]

numbers.sort()
# None

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

1.5. Multiple statements in one line

my_list = [3, 1, 2]

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

1.6. Membership Operators

Table 14. 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]

y contains x

x not in y

x not in [1, 2, 3]

y not contains x

1.7. Built-in functions on sequences

1.7.1. min()

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

min(numbers)
# 1

1.7.2. max()

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

max(numbers)
# 5

1.7.3. sum()

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

sum(numbers)
# 15

1.8. Length of a list

my_list = [1, 2, 3]

len(my_list)
# 3

1.9. Assignments

1.9.1. Create

  • Complexity level: easy

  • Lines of code to write: 3 lines

  • Estimated time of completion: 5 min

  • Filename: solution/list_create.py

Table 15. Pomiary Iris

Sepal length

Sepal width

Petal length

Petal width

Species

5.8

2.7

5.1

1.9

virginica

5.1

3.5

1.4

0.2

setosa

5.7

2.8

4.1

1.3

versicolor

6.3

2.9

5.6

1.8

virginica

6.4

3.2

4.5

1.5

versicolor

  1. Dane są pomiary Table 15.

  2. Każdy z wierszy zapisz jako osobny list

  3. Do przekonwertowania tabelki, wykorzystaj zaznaczanie wielu linijek za pomocą klawisza alt w Twoim IDE