>>> x = [1, 2, 3]
And here is a list of strings.
>>> x = ["Hello", "World"]
List can be heterogeneous. Here is a list containings integers, strings and another list.
>>> x = [1, 2, "Hello", "World", ["Another", "list", "Item"]]
>>> print(x)
[1, 2, 'Hello', 'World', ['Another', 'list', 'Item']]
>>>
The built-in function len works for lists as well.
>>> x = [1, 2, 3]
>>> print(x)
[1, 2, 3]
>>> len(x)
3
>>>
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
>>> my_list = ['l','e','a','r','n']
>>> print(my_list[0])
l
>>> print(my_list[1])
e
>>> print(my_list[2])
a
>>> # Nested List
>>> n_list = ["Happy", [2,0,1,5]]
>>> # Nested indexing
>>> print(n_list[0][1])
a
>>> print(n_list[0][4])
y
>>> print(n_list[1][3])
5
>>>
We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
>>> my_list = ['p','r','o','b','l','e','m']
>>> # delete one item
>>> del my_list[2]
>>> # Output: ['p', 'r', 'b', 'l', 'e', 'm']
>>> print(my_list)
['p', 'r', 'b', 'l', 'e', 'm']
>>> # delete multiple items
>>> del my_list[1:5]
>>> # Output: ['p', 'm']
>>> print(my_list)
['p', 'm']
>>> # delete entire list
>>> del my_list
>>> # Error: List not defined
>>> print(my_list)
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
print(my_list)
NameError: name 'my_list' is not defined
>>>
Methods that are available with list object in Python programming are tabulated below.
They are accessed as list.method()
. Some of the methods have already been used above.
append() | Add an element to the end of the list |
extend() | Add all elements of a list to the another list |
insert() | Insert an item at the defined index |
remove() | Removes an item from the list |
pop() | Removes and returns an element at the given index |
clear() | Removes all items from the list |
index() | Returns the index of the first matched item |
count() | Returns the count of number of items passed as an argument |
sort() | Sort items in a list in ascending order |
reverse() | Reverse the order of items in the list |
copy() | Returns a shallow copy of the list |
>>> my_list = [9, 8, 7, 6, 3, 4, 5, 9]
>>> print(my_list.index(9))
0
>>> print(my_list.count(9))
2
>>> my_list.sort()
>>> print(my_list)
[3, 4, 5, 6, 7, 8, 9, 9]
>>> my_list.reverse()
>>> print(my_list)
[9, 9, 8, 7, 6, 5, 4, 3]
>>>