login

Manipulating Python List

Modifying list elements

To modify list element, you access it via index or slicing and change its content, for example:
 

list = [0,'modify','a','list']
list[0] = 'how to'
print(list) # ['how to', 'modify', 'a', 'list']

Appending the lists

Python supports two functions to allow you to append a list.
Function
Meaning
Append
to append a list as an element of another list
Extend
to append all element of a list to anther list

Here is example of using append and extend functions of list:

a = [1,2,3]
b = [4,5,6]
a.append(b)
print(a) #[1, 2, 3, [4, 5, 6]]
a = [1,2,3]
a.extend(b)
print(a) #[1, 2, 3, 4, 5, 6]

Besides using the extend function, you can also use concatenate operator (+) to append all elements of a list to another.

x = ['one','two','three']
y = ['four','five']
x = x + y
print(x) #['one', 'two', 'three', 'four', 'five']

Sorting the list

A list can be sorted by using built-in sort function. Here is an example of using sort function to sort a list of integer:
 

# sort list by using sort function
list = [1,5,8,4,2,9]
list.sort()
print(list) #[1, 2, 4, 5, 8, 9]

Python also allows you to define custom sorting rule by using a custom key function. First you define a rule of sorting by defining a key function to decide the rule of sorting. Let’s take a look at an example of using custom sort:

# sort list by using sort function with custom key function
def compare(str):
    return len(str)
list = ['A','B','AA','BB','C']

# sort list without using key function
list.sort()
print(list) #['A', 'AA', 'B', 'BB', 'C']

# sort list without using custom key function
list.sort(key=compare)
print(list) #['A', 'B', 'C', 'AA', 'BB']

First we defined a simple function which returns the number of character in a string. Then we sorted the list by using default key function. The list is sorted in alphabet ascending order. After that we used our custom function to pass it to the key parameter of the sort function. At this time instead of comparing element of the list in alphabet order, it compares by number of character of each elements when sorting the list.

Other list operations

List supports many other useful operation which is listed as the table below. You can practice with it until getting familiar.

Operations
Meaning
Examples
Result
*
Use to replicated the list
a = ['A'] * 4
a = [‘A’, ‘A’, ‘A’, ‘A’]
min
Returns the smallest element in a list
list = [1,2,6]
min(list)
1
max
Returns the largest element in a list
list = [1,2,6]
max(list)
6
index
Returns the position of a value in a list
list = [1,2,6]
list.index(2)
1
count
Counts the number of times a value occurs in a list
list=[1,2,2,3,2]
list.count(2)
3
in
Returns whether an item is in a list
list = [1,2,6]
a = 2
b = a in list
print(b)
true