Python List

Anh-Thi Dinh

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):
1x = [1, 2]
2y = [1, 2]
3z = [2, 1]
4
5x == y
6x == z
1True
2False
Mutable (we can change elements in list),
1x = [1, 2, 3]
2x[1] = 5
3print(x)
4
5# change mutiple elements
6y = [1, 2, 3, 4, 5]
7y[1:3] = [20, 30]
8print(y)
1[1, 5, 3]
2[1, 20, 30, 4, 5]

Create

Directly,
1x = [1, "Thi", 3] # mixed datatypes
2y = [[1, 2, 3],
3     [4, 5, 6]] # nested list
4z = [] # empty list
5
6print(x)
7print(y)
8print(z)
1[1, 'Thi', 3]
2[[1, 2, 3], [4, 5, 6]]
3[]
From other types,
1a = (1, 2, 3) # tuple
2x = list(a)
3
4print(a)
5print(x)
1(1, 2, 3)
2[1, 2, 3]
With for (List comprehensions),
1x = [i for i in range(4)]
2print(x)
1[0, 1, 2, 3]
1# list comprehension with if
2[e for e in lst if e>0]
3
4# list comprehension with if else
5[x+1 if x >= 45 else x+5 for x in l]
1# 2 fors in list comprehension
2[(x,y) for x in seq_x for y in seq_y]
3[entry for tag in tags for entry in entries if tag in entry]
4
5a = [[1,2], [3,4]]
6{i for e in a for i in e}
7# {1, 2, 3, 4}
Create a list from range,
1[*range(10, 21, 1)]
1[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
A list of random int numbers,
1random.sample(range(10, 30), 5)
2# [16, 19, 13, 18, 15]

Copy

Don't use y = x directly!
1x = [1, 2, 3]
2y = x
3z = x.copy()
4t = x[:]
5u = list(x)
6
7x[2] = 30 # x changes
8print(x)
9print(y) # y changes with x
10print(z) # z doesn't change
11print(t) # t doesn't change
12print(u) # u doesn't change
1# Output
2[1, 2, 30]
3[1, 2, 30]
4[1, 2, 3]
5[1, 2, 3]
6[1, 2, 3]

Access elements

Normal list (1 dimensional),
1x = [1, 2, 3, 4]
2
3print(x[0]) # single index
4print(x[:2]) # slice
5print(x[-2]) # negative index
1# Output
21
3[1, 2]
43
Nested list,
1y = [[1, 2, 3],
2     [4, 5, 6]]
3
4print(y[0][1]) # single element
5print(y[1]) # row 1
6print([row[1] for row in y]) # column 1
1# Output
22
3[4, 5, 6]
4[2, 5]

Get length

1x = [1, 2, 3, 4]
2y = [[1, 2, 3],
3     [4, 5, 6]]
4
5print(len(x))
6print(len(y)) # number of rows
7print(len(y[0])) # number of columns
8
9import numpy as np
10np.shape(y)
1# Output
24
32
43
5
6(3,4)

Add more elements

1x = [1, 2, 3]
2
3x.append(4) # single element
4print(x)
5
6x.extend([5, 6]) # another list
7print(x)
1# Output
2[1, 2, 3, 4]
3[1, 2, 3, 4, 5, 6]
Add to desired positions,
1x = [1, 2]
2x.insert(30, 3)  # at 30th position --> add to the last
3print(x)
4
5y = [1, 2]
6y.insert(1, 3)
7print(y)
1# Output
2[1, 2, 3]
3[1, 3, 2]
With slices (it likes the intersection between indexes of the current list with indexes indicated in the slice):
1x = [1, 2]
2x[5:7] = [3, 4]
3print(x)
4
5y = [1, 2]
6y[2:2] = [3, 4, 5]
7print(y)
1# Output
2[1, 2, 3, 4]
3[1, 2, 3, 4, 5]

Remove elements

Using the keyword del:
1x = [1, 2, 3, 4, 5]
2print(x)
3
4del x[1]
5print(x)
6
7del x[:2]
8print(x)
9
10del x  # delete entire list
11print(x)
1# Output
2[1, 2, 3, 4, 5]
3[1, 3, 4, 5]
4[4, 5]
5NameError: name 'x' is not defined
Using .remove() to remove a value in list (it removes the first found value):
1x = [1, 2, 3, 4, 3]
2x.remove(3) # remove the first found value "3"
3print(x)
1# Output
2[1, 2, 4, 3]
If you wanna remove all specific value from a list:
1x = [1, 2, 3, 4, 3]
2x = [i for i in x if i != 3]
3print(x)
1# Output
2[1, 2, 4]
Using .pop() to remove and return the deleted element.
1x = [1, 2, 3, 4]
2y = x.pop(2)  # delete at 2nd position
3print(x)
4print(y)
5
6z = x.pop()  # delete the last element
7print(x)
8print(z)
1# Output
2[1, 2, 4]
33
4[1, 2]
54
Using .clear() to empty a list:
1x = [1, 2, 3]
2x.clear()
3print(x)
1# Output
2[]
Special case, using a empty list:
1x = [1, 2, 3, 4]
2x[1:3] = []
3print(x)
1# Output
2[1, 4]

2 lists

Intersection

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

Coupling 2 lists

Using + and * (repeat),
1x = [1, 2, 3]
2print(x + [4, 5, 6])
3print(["re"] * 3)
1# Output
2[1, 2, 3, 4, 5, 6]
3['re', 're', 're']

Sort a list

Return a sorted list but not change the list:
1x = [1, 5, 3, 2, 4]
2print(sorted(x)) # ASC
3print(sorted(x, reverse=True)) # DESC
4print(x) # x doesn't change
1# Output
2[1, 2, 3, 4, 5]
3[5, 4, 3, 2, 1]
4[1, 5, 3, 2, 4]
Sort and change a list:
1x = [1, 5, 3, 2, 4]
2x.sort() # return None, ASC
3print(x) # x does change
4x.sort(reverse=True) # DESC
5print(x)
1# Output
2[1, 2, 3, 4, 5]
3[5, 4, 3, 2, 1]
Sorted with a key function:
1fruits = ['apple', 'banana', 'kiwi', 'pomegranate']
2sorted_fruits = sorted(fruits, key=len)
3print(sorted_fruits)
4
5# Output: Sorted list: ['kiwi', 'apple', 'banana', 'pomegranate']

Reverse a list

1x = [1, 2, 3, 4]
2y = x[::-1] # x doesn't change
3print(x)
4print(y)
5x.reverse() # x changes
6print(x)
1[1, 2, 3, 4]
2[4, 3, 2, 1]
3[4, 3, 2, 1]

Map a function to each element

If you wanna apply a function to each element in an iterable:
1square = lambda x: x * 2
2x = [1, 2, 3, 4] # can be tuple or other iterable
3y = map(square, x) # return a map object
4print(list(y))
1[1, 4, 9, 16]

Get indexes

Get indexes with for

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

Get index of some element

1lst.index(<e>) # Returns the index of the first matched item
2
3lst.index(max(lst)) # get the index of the max in list

Other methods

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