List

List

Mutable, list can be modified
List needs to be in square bracket [], for example: [1,2,3,4,5] or [β€˜a’,’b’,’c’] or [1,2,3,’a’,’b’,’10’]
List is a sequence, iterable
l=[β€˜a’,’b’,’c’]
l[0]=β€œa”
l[1]=β€œb”
l[2]=β€œc”
It is zero based indexing, index starts from zero
List can be iterated through:
1
for i in l:
2
print(i)
Copied!
Convert to List, use function list()
For example:
n=12345
list(n) becomes [1,2,3,4,5]
List is an object, meaning it has methods and attributes that can be invoked
To see all methods, type
help(<list variable>)
In Jupyter notebook, to see list of methods or attributes
Press shift key after enter <list variable>.
1
>>> squares = [1, 4, 9, 16, 25]
2
>>> squares
3
[1, 4, 9, 16, 25]
4
>>> squares[0] # indexing returns the item
5
1
6
>>> squares[-1]
7
25
8
>>> squares[-3:] # slicing returns a new list
9
[9, 16, 25]
10
>>> squares[:]
11
[1, 4, 9, 16, 25]
12
>>> squares + [36, 49, 64, 81, 100]
13
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
14
cubes = [1, 8, 27, 65, 125] # something's wrong here
15
>>> 4**3 # the cube of 4 is 64, not 65!
16
64
17
>>> cubes[3] = 64 # replace the wrong value
18
>>> cubes
19
[1, 8, 27, 64, 125]
20
>>> cubes.append(216) # add the cube of 6
21
>>> cubes.append(7**3) # and the cube of 7
22
>>> cubes
23
[1, 8, 27, 64, 125, 216, 343]
24
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
25
>>> letters
26
['a', 'b', 'c', 'd', 'e', 'f', 'g']
27
>>> # replace some values
28
>>> letters[2:5] = ['C', 'D', 'E']
29
>>> letters
30
['a', 'b', 'C', 'D', 'E', 'f', 'g']
31
>>> # now remove them
32
>>> letters[2:5] = []
33
>>> letters
34
['a', 'b', 'f', 'g']
35
>>> # clear the list by replacing all the elements with an empty list
36
>>> letters[:] = []
37
>>> letters
38
[]
39
>>> letters = ['a', 'b', 'c', 'd']
40
>>> len(letters)
41
4
42
>>> a = ['a', 'b', 'c']
43
>>> n = [1, 2, 3]
44
>>> x = [a, n]
45
>>> x
46
[['a', 'b', 'c'], [1, 2, 3]]
47
>>> x[0]
48
['a', 'b', 'c']
49
>>> x[0][1]
50
β€˜b’
Copied!
Fibonacci series:
the sum of two elements defines the next
1
a, b = 0, 1
2
fib=[]
3
while True:
4
# print(a)
5
if len(fib)>=10:
6
break
7
else:
8
fib.append(a)
9
a, b = b, a+b
10
print(fib[-1], end=" ")
11
Copied!
running it will display:
1
0 1 1 2 3 5 8 13 21 34
Copied!
​
Last modified 1yr ago
Copy link