Thi's avatar
HomeAboutNotesBlogTopicsToolsReading
About|My sketches |Cooking |Cafe icon Support Thi
💌 [email protected]

Python List

Anh-Thi Dinh
Python
Left aside

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):
Mutable (we can change elements in list),

Create

Directly,
From other types,
With for (List comprehensions),
Create a list from range,
A list of random int numbers,

Copy

Don't use y = x directly!

Access elements

Normal list (1 dimensional),
Nested list,

Get length

Add more elements

Add to desired positions,
With slices (it likes the intersection between indexes of the current list with indexes indicated in the slice):

Remove elements

Using the keyword del:
Using .remove() to remove a value in list (it removes the first found value):
If you wanna remove all specific value from a list:
Using .pop() to remove and return the deleted element.
Using .clear() to empty a list:
Special case, using a empty list:

2 lists

Intersection

Coupling 2 lists

Using + and * (repeat),

Sort a list

Return a sorted list but not change the list:
Sort and change a list:
Sorted with a key function:

Reverse a list

Map a function to each element

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

Get elements

Get an element from a list of dictionaries wich condition:

Get indexes

Get indexes with for

Get index of some element

Other methods

  • .count(<e>): Returns the number of item <e> in list.
â—†Generalâ—†Propertiesâ—†Createâ—†Copyâ—†Access elementsâ—†Get lengthâ—†Add more elementsâ—†Remove elementsâ—†2 listsâ—‹Intersectionâ—‹Coupling 2 listsâ—†Sort a listâ—†Reverse a listâ—†Map a function to each elementâ—†Get elementsâ—†Get indexesâ—‹Get indexes with forâ—‹Get index of some elementâ—†Other methods
About|My sketches |Cooking |Cafe icon Support Thi
💌 [email protected]
1x = [1, 2]
2y = [1, 2]
3z = [2, 1]
4
5x == y
6x == z
1True
2False
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]
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[]
1a = (1, 2, 3) # tuple
2x = list(a)
3
4print(a)
5print(x)
1(1, 2, 3)
2[1, 2, 3]
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}
1[*range(10, 21, 1)]
1[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
1random.sample(range(10, 30), 5)
2# [16, 19, 13, 18, 15]
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]
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
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]
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)
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]
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]
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]
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
1x = [1, 2, 3, 4, 3]
2x.remove(3) # remove the first found value "3"
3print(x)
1# Output
2[1, 2, 4, 3]
1x = [1, 2, 3, 4, 3]
2x = [i for i in x if i != 3]
3print(x)
1# Output
2[1, 2, 4]
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
1x = [1, 2, 3]
2x.clear()
3print(x)
1# Output
2[]
1x = [1, 2, 3, 4]
2x[1:3] = []
3print(x)
1# Output
2[1, 4]
1list(set(a) & set(b))
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']
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]
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]
1fruits = ['apple', 'banana', 'kiwi', 'pomegranate']
2sorted_fruits = sorted(fruits, key=len)
3print(sorted_fruits)
4
5# Output: Sorted list: ['kiwi', 'apple', 'banana', 'pomegranate']
1x = [1, 2, 3, 4]
2y = x[::-1] # x doesn't change
3print(x)
4print(y)
5x.reverse() # x changes
6print(x)
1# Output
2[1, 2, 3, 4]
3[4, 3, 2, 1]
4[4, 3, 2, 1]
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# Output
2[1, 4, 9, 16]
1docs = [
2	{"id": 1, "content": "A"},
3	{"id": 2, "content": "B"},
4	{"id": 3, "content": "C"}
5]
6found = next((x for x in docs if x.get('id') == 2), None)
7print(found)
1# Output
2{'id': 2, 'content': 'B'}
1courses = ['a', 'b', 'c']
2for idx, val in enumerate(courses, start=1):
3    print(idx, val)
1# Output
21 a
32 b
43 c
1lst.index(<e>) # Returns the index of the first matched item
2
3lst.index(max(lst)) # get the index of the max in list