REMEMBER PYTHON

MINTE9
2REMEMBER




Lists

p163 Unlinke strings, lists are mutable.
 
>>> numbers = [1, 2]
>>> numbers[1] = 3
>>> numbers
[1, 3]
... 4 lines
˄˄˄
p167 ! The + operator concatenates lists, the * operator repeats a list. The slice operator also works on lists.
 
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
... 5 lines
˄˄˄
 
>>> [2]*4
[2, 2, 2, 2]
... 2 lines
˄˄˄
 
>>> list = ['a', 'b', 'c', 'd']
>>> list[1:3]
['b', 'c']
>>> list[2:]
['c', 'd']
>>> list[:2]
['a', 'b']
... 7 lines
˄˄˄
p168 You can append, extend or sort the list.
 RunCode
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']
... 8 lines
˄˄˄
 CodeCopy
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
... 8 lines
˄˄˄
 CodeCopy
def middle(t):
    res = t[1:-1]
    return res

res = middle([1, 2, 3, 4])
print(res)  # [2, 3]
... 5 lines
˄˄˄

Questions    
No. 17   Dictionaries
CARD
16
32

        A B C D E F
🔔
1/2