In this tutorial you will learn about the Python Lists and its application with practical example.
Python Lists
Python comes with a great built-in sequence data type known as “List”. List is a mutable ordered series of comma-separated values, each of the value as termed as Item. A list variable is defined by having values separated by commas and enclosed within square brackets ([]). A list can hold values of different data types, it means single list can contain strings, integers, as well as objects.
Lists are mutable hence very flexible data type, it mean values or items in a list can be added, removed, and changed any time. Lists are great to deal with data structures like stacks and queues.
Creating Lists
Python list can be defined by simply putting comma-separated values enclosed within square brackets ([ and ]).
Syntax1:-
1 2 |
lst1 = [] # An empty list is created named "lst1" lst2 = [expression1, expression2, ...] # lst2 is the name of the list |
A list having no elements is called an empty list.
Lists can also be created using the built-in list type object as following –
Syntax2:-
1 |
lst1 = list() # empty list |
1 |
lst2 = list(sequence) |
Here, sequence can be any kind of sequence object or iterable. You can also pass in another list, which will makes a copy. Tuples and generators can also be used as sequence object to create a lists.
Syntax3:-
1 |
lst3 = list(expression for variable in sequence) |
Here, expression is evaluated for every item in the sequence to create list items.
In Python, if you assign a list to a variable, python interpreter will never creates a new list for that variable instead both will point to same list object.
1 2 3 4 5 6 |
L1 = L2 = [] # both points to the same list L1 = [] L2 = L1 # both points to the same list L1 = []; L2 = [] # both points to separate lists |
Indexing Lists
1 |
colors= ['red', 'green', 'blue', 'white', 'yellow'] # list of 5 strings. |
Items in the list “colors” are indexed as following –
‘red’ | ‘green’ | ‘blue’ | ‘white’ | ‘yellow’ |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
Negative indexing for the items in the list “colors” can be seen as following –
‘red’ | ‘green’ | ‘blue’ | ‘white’ | ‘yellow’ |
---|---|---|---|---|
-5 | -4 | -3 | -2 | -1 |
Accessing Lists
An list elements can be accessed easily by index or subscript like list_name[index]. Indexing for any lists starts from zero (0) to the last element of a list is list_name[size-1] where size is the number of elements in the list.
Syntax:-
1 |
<list_name>[index] |
Example:-
1 |
L[i] |
here, L[i] returns the item at index i (Indexing for any lists starts from zero (0))
1 |
L[i:j] |
here, L[i:j] returns a new list, containing the items between index i and j; here i represents the start index and j represents the end index. If the specified index is outside the list, Python raises an IndexError exception.
Example:- List elements can be accessed in numerous way as following –
1 2 3 4 5 6 7 8 9 |
colors= ['red', 'green', 'blue', 'white', 'yellow'] # list of 5 strings. nums= [2, 5, 8, 10, 15] # list of 5 numbers. mixedlist= [2, 5, 8, 'blue', 'john'] # lists can contain different variable types. print colors[0] print colors[0:2] print nums[-3:-1] print colors[0:] print nums[:2] |
Output:-
1 2 3 4 5 |
red ['red', 'green'] [8, 10] ['red', 'green', 'blue', 'white', 'yellow'] [2, 5] |
Delete Item from a List
An items from a list can removed simply using the del statement. This will remove the value at the given index. The del statement can be used to delete a single or multiple items from the given list, it can also be used to delete entire list.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
colors= ['red', 'green', 'blue', 'white', 'yellow'] # list of 5 strings. # delete one item del colors[2] # Output: ['red', 'green', 'white', 'yellow'] print(colors) # delete multiple items del colors[1:5] # Output: ['red'] print(colors) # delete entire list del colors # Error: List not defined print(colors) |
Output:-
1 2 3 4 5 6 |
['red', 'green', 'white', 'yellow'] ['red'] Traceback (most recent call last): File "list_del.py", line 19, in <module> print(colors) NameError: name 'colors' is not defined |
Iterating Through a List
The for-in statement makes it easy to loop over the items in a list:
1 2 |
for item in L: print item |
If you need both the index and the item, use the enumerate function:
1 2 |
for index, item in enumerate(L): print index, item |
If you need only the index, use range and len:
1 2 |
for index in range(len(L)): print index |
Updating Lists
As Python lists are mutable, you can easily update an individual items or slices of the given list.
Syntax:- dfgdg
1 |
<list_name>[index]=<value> |
Example:- gdgdfg
1 2 3 4 |
colors= ['red', 'green', 'blue', 'white', 'yellow'] # list of 5 strings. # change the 1st item colors[0]="orange" print(colors) |
Output:-
1 |
['orange', 'green', 'blue', 'white', 'yellow'] |
you can update a list slice as following –
Example:-
1 2 3 4 5 6 7 |
colors= ['red', 'green', 'blue', 'white', 'yellow'] # list of 5 strings. # change the 1st item colors[0]="orange" print(colors) # change 2nd to 4th items colors[1:4] = ['black', 'purple', 'pink'] print(colors) |
Output:-
1 2 |
['orange', 'green', 'blue', 'white', 'yellow'] ['orange', 'black', 'purple', 'pink', 'yellow'] |
If you want to add one item to a given list or several items to a list, it can be done using append() and extend() method respectively.
1 2 3 4 5 6 7 8 9 10 11 |
odd = [1, 3, 5] odd.append(7) # Output: [1, 3, 5, 7] print(odd) odd.extend([9, 11, 13]) # Output: [1, 3, 5, 7, 9, 11, 13] print(odd) |
Slicing Lists
In Python, you can also extract a sub list from a given list. It can be done as following –
Syntax:-
1 |
sliced_list = <list_name>[<start_index>:<end_index>] |
Here, a sub list is extracted from given list starting from start_index and stopping just before end_index. The default values for start_index and the end_index is zero(0).
If you omit the start_index (before the colon), the slice starts from the beginning of the list. If you omit the end_index, the slice goes to the end of the list. If you omit both, it will return a copy of the given list.
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
colors= ['red', 'green', 'blue', 'white', 'yellow'] # list of 5 strings. #indices start at 0 and end at 3 print(colors[0:2]) # cut first two items #['red', 'green'] print(colors[1:2]) # cut second item #['green'] print(colors[1:-2]) #['green', 'blue'] print(colors[:3]) # cut first three items #['red', 'green', 'blue'] print(colors[:]) # Creates copy of original list |
Output:-
1 2 3 4 5 |
['red', 'green'] ['green'] ['green', 'blue'] ['red', 'green', 'blue'] ['red', 'green', 'blue', 'white', 'yellow'] |