index

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:

for i in l:

print\(i\)

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>.

>>> squares = [1, 4, 9, 16, 25]

>>> squares

[1, 4, 9, 16, 25]

>>> squares[0] # indexing returns the item

1

>>> squares[-1]

25

>>> squares[-3:] # slicing returns a new list

[9, 16, 25]

>>> squares[:]

[1, 4, 9, 16, 25]

>>> squares + [36, 49, 64, 81, 100]

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

cubes = [1, 8, 27, 65, 125] # something's wrong here

>>> 4 ** 3 # the cube of 4 is 64, not 65!

64

>>> cubes[3] = 64 # replace the wrong value

>>> cubes [1, 8, 27, 64, 125]

>>> cubes.append(216) # add the cube of 6

>>> cubes.append(7**3) # and the cube of 7

>>> cubes

[1, 8, 27, 64, 125, 216, 343]

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> letters

['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> # replace some values

>>> letters[2:5] = ['C', 'D', 'E']

>>> letters

['a', 'b', 'C', 'D', 'E', 'f', 'g']

>>> # now remove them

>>> letters[2:5] = []

>>> letters

['a', 'b', 'f', 'g']

>>> # clear the list by replacing all the elements with an empty list

>>> letters[:] = []

>>> letters

[]

>>> letters = ['a', 'b', 'c', 'd']

>>> len(letters)

4

>>> a = ['a', 'b', 'c']

>>> n = [1, 2, 3]

>>> x = [a, n]

>>> x

[['a', 'b', 'c'], [1, 2, 3]]

>>> x[0]

['a', 'b', 'c']

>>> x[0][1]

‘b’

# Fibonacci series:

# the sum of two elements defines the next

a, b = 0, 1

fib=[]

while True:

# print(a)

if len\(fib\)&gt;=10:

    break

else:

    fib.append\(a\)

    a, b = b, a+b print\(fib\[-1\]\)

Last updated