Similar to strings, lists also have many utility methods. Yet, if string methods don’t modify the initial string and return a new one, list methods make changes to the initial list itself.
Method
Description
Examples
Results
Alternative
count(x)
Count the number of occurrences of x
l.count(0)
3
-
clear()
Make the list empty
l.clear()
-
l = []
del l[:]
l *= 0
copy()
Copy and return the list
new = l.copy()
-
new = l[:]
new = list(l)
new = copy.copy(l)
index(x)
Find the first occurrence of x (ValueError if not in the list)
l.index(0)
5
-
insert(pos, x)
Insert x at position pos
l.insert(1, 7)
[1, 7, 1]
l = l[:pos] + [x] + l[pos:]
remove(x)
Remove x from the list (ValueError if not in the list)
l.remove(7)
[1, 1]
-
reverse()
Reverse the list
l.reverse()
-
l = l[::-1]
sort()
Sort the list in increasing order
l.sort()
-
l = sorted(l)
Again, most of the names are very intuitive. Yet, it’s not mandatory to remember them all. A quick googling will give you the needed results. These examples are for demonstration purposes. To show what is possible with Python lists.
Challenge
Given n numbers, you are asked to sort them in ascending order and print them in the output.
The first line of the input contains a single number n. The next n lines contain integers each on a separate line.
The program should output all the numbers on a single line in increasing order separated by a space.