# Python List

26-11-2020 / Edit on Github

## General #

• Index starts with 0.
• Slice: x[1:4] gives elements from x[1] to x[3] inclusive (takes 1, not 4).
• x[:3] + x[3:] gives exactly x.

## Properties #

Ordered (different order, different list):

x = [1, 2]y = [1, 2]z = [2, 1]x == yx == z
True
False


Mutable (we can change elements in list),

x = [1, 2, 3]x[1] = 5print(x)# change mutiple elementsy = [1, 2, 3, 4, 5]y[1:3] = [20, 30]print(y)
[1, 5, 3]
[1, 20, 30, 4, 5]


## Create #

Directly,

x = [1, "Thi", 3] # mixed datatypesy = [[1, 2, 3],     [4, 5, 6]] # nested listz = [] # empty listprint(x)print(y)print(z)
[1, 'Thi', 3]
[[1, 2, 3], [4, 5, 6]]
[]


From other types,

a = (1, 2, 3) # tuplex = list(a)print(a)print(x)
(1, 2, 3)
[1, 2, 3]


With for (List comprehensions),

x = [i for i in range(4)]print(x)
[0, 1, 2, 3]

# list comprehension with if[e for e in lst if e>0]# list comprehension with if else[x+1 if x >= 45 else x+5 for x in l]
# 2 fors in list comprehension[(x,y) for x in seq_x for y in seq_y][entry for tag in tags for entry in entries if tag in entry]a = [[1,2], [3,4]]{i for e in a for i in e}# {1, 2, 3, 4}

Create a list from range,

[*range(10, 21, 1)]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


A list of random int numbers,

random.sample(range(10, 30), 5)# [16, 19, 13, 18, 15]

## Copy #

Don't use y = x directly!

x = [1, 2, 3]y = xz = x.copy()t = x[:]u = list(x)x[2] = 30 # x changesprint(x)print(y) # y changes with xprint(z) # z doesn't changeprint(t) # t doesn't changeprint(u) # u doesn't change
[1, 2, 30]
[1, 2, 30]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]


## Access elements #

Normal list (1 dimensional),

x = [1, 2, 3, 4]print(x[0]) # single indexprint(x[:2]) # sliceprint(x[-2]) # negative index
1
[1, 2]
3


Nested list,

y = [[1, 2, 3],     [4, 5, 6]]print(y[0][1]) # single elementprint(y[1]) # row 1print([row[1] for row in y]) # column 1
2
[4, 5, 6]
[2, 5]


## Get length #

x = [1, 2, 3, 4]y = [[1, 2, 3],     [4, 5, 6]]print(len(x))print(len(y)) # number of rowsprint(len(y[0])) # number of columnsimport numpy as npnp.shape(y)
4
2
3

(3,4)


x = [1, 2, 3]x.append(4) # single elementprint(x)x.extend([5, 6]) # another listprint(x)
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]


x = [1, 2]x.insert(30, 3)  # at 30th position --> add to the lastprint(x)y = [1, 2]y.insert(1, 3)print(y)
[1, 2, 3]
[1, 3, 2]


With slices (it likes the intersection between indexes of the current list with indexes indicated in the slice):

x = [1, 2]x[5:7] = [3, 4]print(x)y = [1, 2]y[2:2] = [3, 4, 5]print(y)
[1, 2, 3, 4]
[1, 2, 3, 4, 5]


## Remove elements #

Using the keyword del:

x = [1, 2, 3, 4, 5]print(x)del x[1]print(x)del x[:2]print(x)del x  # delete entire listprint(x)
[1, 2, 3, 4, 5]
[1, 3, 4, 5]
[4, 5]
NameError: name 'x' is not defined


Using .remove() to remove a value in list (it removes the first found value):

x = [1, 2, 3, 4, 3]x.remove(3) # remove the first found value "3"print(x)
[1, 2, 4, 3]


If you wanna remove all specific value from a list:

x = [1, 2, 3, 4, 3]x = [i for i in x if i != 3]print(x)
[1, 2, 4]


Using .pop() to remove and return the deleted element.

x = [1, 2, 3, 4]y = x.pop(2)  # delete at 2nd positionprint(x)print(y)z = x.pop()  # delete the last elementprint(x)print(z)
[1, 2, 4]
3
[1, 2]
4


Using .clear() to empty a list:

x = [1, 2, 3]x.clear()print(x)
[]


Special case, using a empty list:

x = [1, 2, 3, 4]x[1:3] = []print(x)
[1, 4]


## 2 lists #

### Intersection #

list(set(a) & set(b))

### Coupling 2 lists #

Using + and * (repeat),

x = [1, 2, 3]print(x + [4, 5, 6])print(["re"] * 3)
[1, 2, 3, 4, 5, 6]
['re', 're', 're']


## Sort a list #

Return a sorted list but not change the list:

x = [1, 5, 3, 2, 4]print(sorted(x)) # ASCprint(sorted(x, reverse=True)) # DESCprint(x) # x doesn't change
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[1, 5, 3, 2, 4]


Sort and change a list:

x = [1, 5, 3, 2, 4]x.sort() # return None, ASCprint(x) # x does changex.sort(reverse=True) # DESCprint(x)
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]


## Reverse a list #

x = [1, 2, 3, 4]y = x[::-1] # x doesn't changeprint(x)print(y)x.reverse() # x changesprint(x)
[1, 2, 3, 4]
[4, 3, 2, 1]
[4, 3, 2, 1]


## Map a function to each element #

If you wanna apply a function to each element in an iterable:

square = lambda x: x * 2x = [1, 2, 3, 4] # can be tuple or other iterabley = map(square, x) # return a map objectprint(list(y))
[1, 4, 9, 16]


## Get indexes #

### Get indexes with for #

courses = ['a', 'b', 'c']for idx, val in enumerate(courses, start=1):    print(idx, val)
1 a
2 b
3 c


### Get index of some element #

lst.index(<e>) # Returns the index of the first matched itemlst.index(max(lst)) # get the index of the max in list

## Other methods #

• .count(<e>): Returns the number of item <e> in list.