PROGRAMMING

m9/ PYTHON
REMEMBERS




Lists

p163 Unlinke strings, lists are mutable.
 
>>> numbers = [1, 2]
>>> numbers[1] = 3
>>> numbers
[1, 3]
p167 ! The + operator concatenates lists.
 
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
The * operator repeats a list.
 
>>> [2]*4
[2, 2, 2, 2]
The slice operator also works on lists.
 
>>> list = ['a', 'b', 'c', 'd']
>>> list[1:3]
['b', 'c']
>>> list[2:]
['c', 'd']
>>> list[:2]
['a', 'b']
... 1 lines
 
Operations    (2/2)

Operations

p168 You can append, extend or sort the list.
 
A = ['a', 'b', 'c']
A.append('d')
print(A)  # ['a', 'b', 'c', 'd']

B = ['d', 'e']
A.extend(B)
print(A)  # ['a', 'b', 'c', 'd', 'd', 'e']

A.reverse()
print(A)  # ['e', 'd', 'd', 'c', 'b', 'a']
... 2 lines
 
 
def nested_sum(t):
    total = 0
    for el in t:
        total += sum(el)
    return total

t = [[1, 2], [3], [4, 5, 6]]
sum = nested_sum(t)
print(sum)  # 21
... 2 lines
 
 
def middle(t):
    res = t[1:-1]
    return res

res = middle([1, 2, 3, 4])
print(res)  # [2, 3]

Questions    
Dictionaries

        A B C D E F
🔔
1/2