Lesson 1 ❮ Lesson List ❮ Top Page
❯ 1.5 List Methods
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 10m 21s
☷ Interactive readings 5m
There are two ways to add a new element to a list.
append(item)
adds item to the end of list.
insert(pos, item)
adds item to the index pos in the list.
You can use the following method to delete element of a list.
pop(pos)
deletes the element with index pos (default is -1). It is also possible to save the popped item into a variable.
remove(itemname)
deletes the element with the name itemname.
Sorting elements in a list can be done easily using the following:
sort()
sorts the list.
reverse()
reverses the order of a list.
You can combine two lists by the following:
list1.extend(list2)
combines list1 with list2.
To make a separate list, use + instead.
You can get the index and the count number of an item name in a list using the following:
index(itemname)
returns the index of the first element with the name itemname.
count(itemname)
returns the number of elements with the name itemname.
The list methods in this lesson can be applied as well to a string. Each character in a string can be treated like a single item in a list.
Some methods can be used with or without assigning it to a variable, like pop(). However, assigning other methods to a variable will return a NoneType object. This will give an AttributeError.
To fix this error, remove names = from Line 3 and 4.