Python’s list type (part 4) — Operations on lists
In part 4, we will learn
- Regular operations on lists
- Inplace operations on lists
- Unpack a list
Operations that don’t change a list
These operations operate on lists and return some values, but don’t modify the contents of the lists.
First, initialze two list
x = [2, 7, -3, 11.5, True, 2]
y = ["A", 1, 58.5, 94, [12, 20]]print(x)
print(y)[2, 7, -3, 11.5, True, 2]
['A', 1, 58.5, 94, [12, 20]]
Count the number of elements
len(x)6
Check membership
# Check if 2 is in x
2 in xTrue# Check if 99 is in x
99 in xFalse
Count the number of occurrences of a value
# Count how many times True occurs
x.count(True)1# Count how many times 2 occurs
x.count(2)2# Count how many times 99 occurs
x.count(99)0
Concatenate 2 lists
# Elements of x then elements of y
x + y[2, 7, -3, 11.5, True, 2, 'A', 1, 58.5, 94, [12, 20]]# Elements of y then elements of x
y + x['A', 1, 58.5, 94, [12, 20], 2, 7, -3, 11.5, True, 2]# Note that this operation doesn't change x and y
print(x)
print(y)[2, 7, -3, 11.5, True, 2]
['A', 1, 58.5, 94, [12, 20]]# To save the result from a concatenation
# You need to assign it to some variable
z = x + y
z[2, 7, -3, 11.5, True, 2, 'A', 1, 58.5, 94, [12, 20]]
Replicate a list
# Replicate x 3 times
x * 3[2, 7, -3, 11.5, True, 2, 2, 7, -3, 11.5, True, 2, 2, 7, -3, 11.5, True, 2]# Similarly, x is unchanged
x[2, 7, -3, 11.5, True, 2]
Sort a list (if possible)
# We can sort x because
# True can be treated as 1
sorted(x)[-3, True, 2, 2, 7, 11.5]# However, we cannot sort y
# Because its element are not compatible
# (cannot compare a string to a number or a list)
# Try it yourself to see the error# Sort values in descending order
sorted(x, reverse=True)[11.5, 7, 2, 2, True, -3]# Of course, x is unchanged
x[2, 7, -3, 11.5, True, 2]# To save the sorted values
# You need an assignment
z = sorted(x)
z[-3, True, 2, 2, 7, 11.5]
Get the index of the first occurence of a value
# Index of the first value 2
# returns 0 (first position)
x.index(2)0# Index of the first value True
# returns 4 (fifth position)
x.index(True)4# If the value is not in the list
# You will get an error
# Try x.index(99)
Operations that change a list
These operations make some changes to a list, and often return None
. They are often called "inplace" operation (happen inplace and save changes to the list).
Note that inplace operations are only available for mutable data types (Ex: lists, dictionaries, sets). For immutable types (Ex: numbers, tuples, ranges, frozensets) the objects cannot change after created, thus will not have inplace methods.
First, initialize a list
x = [2, 7, -3, 11.5, 2, True]
print(x)
print(id(x))[2, 7, -3, 11.5, 2, True]
1893914337600
Reverse a list
# No assignment is needed
x.reverse()
x[True, 2, 11.5, -3, 7, 2]# If you mistakenly assign x = x.reverse()
# You will get None back, because x.reverse() reverses x
# saves the change, and returns None
# then you re assign this None back to x
# then it overwrites the reversed values
# Now try to use y = x.reverse() to avoid messing up x
y = x.reverse()
print(y)None# Since you call x.reverse() twice
# you get back the original order
x[2, 7, -3, 11.5, 2, True]
Sort a list
# Ascending sort
x.sort()
x[-3, True, 2, 2, 7, 11.5]# Descending sort
x.sort(reverse=True)
x[11.5, 7, 2, 2, True, -3]
Append an element to the end of the list
# Append 99
x.append(99)
x[11.5, 7, 2, 2, True, -3, 99]# Append a list ['A', 'B']
x.append(['A', 'B'])
x[11.5, 7, 2, 2, True, -3, 99, ['A', 'B']]
Extend a list by adding multiple elements to the end of the list
# Adding 55, 66 as two last elements
x.extend([55, 66])
x[11.5, 7, 2, 2, True, -3, 99, ['A', 'B'], 55, 66]
Insert an element into a given position
# Insert 100 into the 2nd position
x.insert(1, 100)
x[11.5, 100, 7, 2, 2, True, -3, 99, ['A', 'B'], 55, 66]
Remove the first occurence of a value
# Initialize a another list
a = [1, 2, 4, 3, 4, 4]
a.remove(4)
a[1, 2, 3, 4, 4]
Delete an element by index
# Delete the second element
del x[1]
x[11.5, 7, 2, 2, True, -3, 99, ['A', 'B'], 55, 66]
Pop out the last value, and delete it from the list
# Last element of x is assigned to p
# and deleted from x
p = x.pop()# Let's check x and p
print(x)
print(p)[11.5, 7, 2, 2, True, -3, 99, ['A', 'B'], 55]
66# We can choose to pop at a given index
# For example, pop the first element
p = x.pop(0)
print(x)
print(p)[7, 2, 2, True, -3, 99, ['A', 'B'], 55]
11.5
Clear all element
# Empty the contents inside the object
# but still keeping the object
x.clear()
x[]# Confirm the object is the same
id(x)1893914337600
Suppose we use a list to store date data. For example
my_date = [2022, 4, 1]
my_date[2022, 4, 1]
Now, suppose we want to extract each of the elements of my_date
into three variables y
, m
, d
. One way to do it is through three assignment as follows.
y = my_date[0]
m = my_date[1]
d = my_date[2]
But there’s a faster way to do it.
# Unpack three elements into y, m, d
y, m, d = my_date# Confirm
print(y)
print(m)
print(d)2022
4
1
Sometimes, if we want to extract some elements and ignore the others, we can use _
for the unwanted variables so that we don't have to waste time thinking names for them.
# Get date, month only
_, m, d = my_date
print(m)
print(d)4
1# Get year only
y, _, _ = my_date
print(y)2022# Get year only, but faster
# Here, *_ means we don't care about the rest
# Just ignore all of them, regarless how many
y, *_ = my_date
print(y)2022
Unpack a list
Suppose we use a list to store date data. For example
my_date = [2022, 4, 1]
my_date[2022, 4, 1]
Now, suppose we want to extract each of the elements of my_date
into three variables y
, m
, d
. One way to do it is through three assignment as follows.
y = my_date[0]
m = my_date[1]
d = my_date[2]
But there’s a faster way to do it.
# Unpack three elements into y, m, d
y, m, d = my_date# Confirm
print(y)
print(m)
print(d)2022
4
1
Sometimes, if we want to extract some elements and ignore the others, we can use _
for the unwanted variables so that we don't have to waste time thinking names for them.
# Get date, month only
_, m, d = my_date
print(m)
print(d)4
1# Get year only
y, _, _ = my_date
print(y)2022# Get year only, but faster
# Here, *_ means we don't care about the rest
# Just ignore all of them, regarless how many
y, *_ = my_date
print(y)2022
Navigation
Previous: Python’s list type (part 3) — Shallow vs. deep copying
Next: TBU