Listy (typ list)¶

Przykłady podobne (nie identyczne) do pokazanych na wykładzie w interpreterze.
Więcej: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

Pewne operacje listowe¶

In [1]:
lst = [1, 2, 3]

Doklej 10:

In [2]:
lst.append(10)
lst
Out[2]:
[1, 2, 3, 10]

Rozszerzanie list o ciąg (obiekt iterowalny):

In [3]:
lst.extend("abb")
lst
Out[3]:
[1, 2, 3, 10, 'a', 'b', 'b']

Wstaw "X" pod indeks 2 (rozsuwajac listę):

In [4]:
lst.insert(2, "X")
lst
Out[4]:
[1, 2, 'X', 3, 10, 'a', 'b', 'b']

Usuń element spod indeksu 3 (nie metodą):

In [5]:
del lst[3]
lst
Out[5]:
[1, 2, 'X', 10, 'a', 'b', 'b']

Usuń element spod indeksu 3 (metodą listy):

In [6]:
a = lst.pop(3) 
print(a, lst)
10 [1, 2, 'X', 'a', 'b', 'b']

Usuń pierwsze wystapienie "X" na liscie:

In [7]:
lst.remove("X")
lst
Out[7]:
[1, 2, 'a', 'b', 'b']

Pod którym indeksem jest pierwsze wystąpienie 'a'?

In [8]:
lst.index('a')  # por. s.index(x, start, end)
Out[8]:
2

Ile razy 'b' jest na liście?

In [9]:
lst.count('b')
Out[9]:
2

Odwroć listę:

In [10]:
lst.reverse()
lst
Out[10]:
['b', 'b', 'a', 2, 1]

Posortuj listę (niemalejąco):

In [11]:
lst = [4, 2, 5, 1, 6]
lst.sort() # por. s.sort(reverse=True)
lst
Out[11]:
[1, 2, 4, 5, 6]

Usuń wszystkie elementy z listy:

In [12]:
lst.clear()
lst
Out[12]:
[]

Kopiowanie list (ale nie obiektów z list!), trzy sposoby:

In [13]:
lst = [1, 2, 3]
a = lst.copy()
b = lst[:] # patrz: slicing
c = list(lst)
print(a, b, c)
[1, 2, 3] [1, 2, 3] [1, 2, 3]

Inne operacje (np. minimum, maksimum, suma listy):

In [14]:
lst = [34, 676, 234, 56]
print(max(lst), min(lst), len(lst), sum(lst))
print(sorted(lst))
print(list(reversed(lst)))
# reversed(lst) - obiekt iterowalny (ale nie lista)
676 34 4 1000
[34, 56, 234, 676]
[56, 234, 676, 34]

(Extended) slicing¶

Slicing - podobny do indeksowania, ale dotyczy kawałków (wycinków) list.

In [15]:
lst = list(range(10))
print(lst[2:6])
print(lst[2:])
print(lst[:5])
[2, 3, 4, 5]
[2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]
In [16]:
lst[3:6] = "abcdef"
lst
Out[16]:
[0, 1, 2, 'a', 'b', 'c', 'd', 'e', 'f', 6, 7, 8, 9]

Extended slicing:

In [17]:
lst = list(range(10))
print(lst[::2])
lst[::-2] = [100, 101, 102, 103, 104]
print(lst)
[0, 2, 4, 6, 8]
[0, 104, 2, 103, 4, 102, 6, 101, 8, 100]