How Can We Help?
In this tutorial, we are going to explain how to use Python lists with basic syntax and many examples for better understanding.
What is a list in Python ?
List is a form of data collection where different type of data can be stored and separated by commas(,). List is enclosed in pair of square brackets[] and holds all values in a given order.
A list could have a nested list which is in place of any item of the list.
Syntax:
(list_variable_name)=[value1, value2,value3…]
Example (1)
# single data type list
List1=['Country','State','City']
print(List1)
Output:
[‘Country’, ‘State’, ‘City’]
Explanation:
In the above example, ‘List1’ is a list variable name, ‘Country ,State and City’ are list values and list is a string type.
Note: String values of list always represent in the quotation marks.
List can be number, string or both. The values in it need not be of the same type.
Example (2)
# multi data type list
myList=[1,'Python',5.2,'language!']
print(myList)
Output:
[1, ‘Python’, 5.2, ‘language!’]
Explanation:
In the above example, ‘myList’ is a list variable name and ‘1, Python, 5.2 and language!’ are list values which are not of same data type.
Note: List is mutable that means it can be changed.
Python Empty List:
The empty list is written as two square brackets[], i.e. containing nothing.
list1=[], mylist=[]
Explanation:
In the above Example, ‘list1’ and ‘mylist’ are list variable name and two square brackets[] shows empty list values.
Python Single Value List
A single value list is containing only single value with comma and enclosed in pair of square brackets[].
number=[11,] , alphabet=['abc',]
Explanation:
In the above Example, ‘number’ and ‘alphabet’ are list variable name and the values as [11,] and [‘abc’,] shows the list with single values respectively.
Python Multiple Lists Assignment:
We can assign multiple list with its values in a single line by multiple list assignment.
Example (3)
# multiple lists assignment
number, alphabet= [1,2,3] , ['a','b','c']
print('number:',number)
print('alphabet:',alphabet)
Output:
number: [1, 2, 3]
alphabet: [‘a’, ‘b’, ‘c’]
Explanation:
In the above Example, number and alphabet is list variable name and [1,2,3] and [‘a’, ‘b’, ‘c’] are respective values.
Note: Internal Memory Organization of List as list do not store the elements directly at the index. In fact a reference is stored at each index which subsequently refers to the object stored somewhere in the memory. This is due to the fact that some objects may be large enough than other objects and hence they are stored at some other memory location.”
Accessing Python Lists Values
In Python, lists are stored as individual value in a nearby memorylocation. We can access the individual values in a list through indexing from both the directions in forward and backward.
We use the square brackets [] along with the index (i.e. [0],[1] etc) to access the list value available at that index position. Lists use positive index like 0,1,2… and negative index like -1,-2,-3…..to access the values.
Python Lists with positive and negative indexing:
Let’s take, list variable as myList=[ 1,’Ruby’,2,’C#’,3,’Python’]
In the above image, we have given indexing to list values [1,’Ruby’,2,’C#’,3,’Python’). The positive indexing is shown in left to right direction and negative indexing is shown from right to left direction, same like string and tuple data type. To access the list values, we have to call the list index, as per below syntax.
Syntax:
(list_variable_name)[list index]
Example (4)
myList=[1,'Ruby',2,'C#',3,'Python']
# original list values
print(' myList=', myList)
# list values after accessing the index [0] and [-2]
print('0th and 4th position list values:' ,myList[0],myList[-2])
Output:
myList=[1,’Ruby’,2,’C#’,3,’Python’]
0th and 4th position list values: 1 3
Explanation:
In the above Example, for list variable ‘myList’, we are accessing the 0th and 4th position of list values by positive index [0] and negative index [-2] respectively as myList[0], myList[-2]. Therefore, in print statement output is 1 which is at 0th and -6th position of list and 3 which is at 4th and -2th position of list. (See Fig. 1 for list position).
Check This: Article on How to Compare two Lists in Python if you want to know more about different techniques to compare two lists with practical examples.
Out of Range Python Lists Index:
If we try to access the index of list which is not a part of list, then it raises an index error exception.
Example (5)
alphabet=['a','b','c']
# out of range list index
print(alphabet[3])
Output:
Traceback (most recent call last):
File “”, line 1, in
alphabet=[‘a’,’b’,’c’];print(alphabet[3])
IndexError: list index out of range
Explanation:
In the above Example, ‘alphabet’ is list variable name and it has 3 values only which has index as 0,1 and 2 but here, we are accessing 3rd index value by alphabet[3] in print statement ,which is not a part of list, so we got an IndexError as ‘list index out of range’ in output.
Substring and Slicing in Python lists
Accessing a contiguous sequenceof values from a list is called a substring and the process used for substring is called slicing. We can slice a list in both (left and right) direction same as list indexing.
Syntax:
(list_variable_name)[start position : end position]
(list_variable_name)[start position:]
(list_variable_name)[:end position]
(list_variable_name)[:] # any position is not mentioned so include whole list
(list_variable_name)[start position : end position: increment step]
Explanation:
Here, start and end positions should be integer value and increment step can be positive (forward direction increment) or negative (backward direction increment) integer value and not greater than length of list. We can choose any syntax from above syntax list against program requirement.
Note: Lists slicing don’t consider the end position or index value after colon(:).
Example (6)
myList=['Java','Ruby','C','C#','.Net','Python']
# list values after slicing [1:3]
print('1st to 3rd position tuple values:' ,myList[1:3])
Output:
‘1st to 3rd position list values: [‘Ruby’, ‘C’]
Explanation:
In the above Example, for list variable ‘myList’, we are accessing the list values between 1st to 3rd position by myList[1:3]. Output is received as ‘Ruby’ which is at 1st position of list and ‘C’ which is at 2nd position of list. Here, we have considered only 1st and 2nd position of list as 3rd position of list is not considered as the end position because slicing will not accept the values after colon(:).
Example (7)
myList=['Java','Ruby','C','C#','.Net','Python']
# list values after slicing [1:]
print(myList[1:])
Output:
[‘Ruby’, ‘C’, ‘C#’, ‘.Net’, ‘Python’]
Explanation:
In the above Example, for list variable ‘myList’, we are accessing the list values from 1st position to end position of list by myList[1:]. Output is received as [‘Ruby’, ‘C’, ‘C#’, ‘.Net’, ‘Python’] which is excluding the 0th position of list. Here, end position is not mentioned in program so output shows all values of list from 1st index to last index because start position is 1.
Example (8)
myList=['Java','Ruby','C','C#','.Net','Python']
# list values after slicing [:4]
print(myList[:4])
Output:
[‘Java’, ‘Ruby’, ‘C’, ‘C#’]
Explanation:
In the above Example, for list variable ‘myList’, we are accessing the list values up to 4th position of list by myList[:4]. Output is received as [‘Java’, ‘Ruby’, ‘C’, ‘C#’] which shows list values from 0th position to 3rd position. Here, 4th position is not considered because slicing not consider index values after colon(:), so the output is taken from 0th position as start position because list always start with 0th position and in program, start position is not mentioned.
Example (9)
myList=['Java','Ruby','C','C#','.Net','Python']
# list values after slicing [ : ]
print(myList[:])
Output:
(‘Java’, ‘Ruby’, ‘C’, ‘C#’, ‘.Net’, ‘Python’)
Explanation:
In the above Example, for list variable ‘myList’, start and end position of list value is not mentioned in slicing code by myList[:] so output shows all values of list as [‘Java’, ‘Ruby’, ‘C’, ‘C#’, ‘.Net’, ‘Python’] which shows list values from 0th index to last index as explained already.
In python, we can easily reverse the list by using one line code as (list_variable_name)=[::-1]
Example (10)
myList=['Java','Ruby','C','C#','.Net','Python']
print("Reverse list : ", myList[::-1])
Output:
Reverse list : [‘Python’, ‘.Net’, ‘C#’, ‘C’, ‘Ruby’, ‘Java’]
Explanation:
In the above Example, for list variable ‘myList’, start and end position of list value is not mentioned in slicing code (i.e.[:]) so we have to take whole list against understanding of previous examples and 3rd element is -1 ,which denotes that we have to count the elements from backward side (i.e. -1th position element as ‘Python’). So output shows all the values of list from the backward side as [‘Python’, ‘.Net’, ‘C#’, ‘C’, ‘Ruby’, ‘Java’] (i.e. -1th index to -6th index).
Update Python Lists :
We can update a list by modifying an existing entry of value of list. To change the value of particular index of a list, assign the new value to that particular index of the List.
Syntax:
(list_name)[index] = (value)
Example (11)
num=[1,2,6,7]
num[0]=22
print("Updated list: ",num)
Output:
Updated list: [22, 2, 6, 7]
Explanation:
In the above Example , we are updating a value of element 0 of list num by 22 as num[0]=22 and list is mutable so output shows updated list as [22, 2, 6, 7].
List Built-In Functions:
Python has following built-in list functions.
Sr. | Function | Description |
1 | min(list) | It returns a minimum value of a list. |
2 | max(list) | It returns a maximum value of a list. |
3 | len(list) | It returns total length of a list, which is equal to the number of elements in the list. |
4 | type(list) | It returns type of list , if passed variable is a list. |
5 | list(seq) | It converts a sequence/string into a list. |
6 | del(list) | It deletes whole list or individual list element or all element of a list. |
Python lists Basic operations :
We can do following basic operations on list.
Sr. | Operation | Description |
1 | Concatenation(‘+’) | It adds two lists. |
2 | Repetition(‘*’) | It repeats element of list. |
3 | Membership(‘in’ & ‘not in’) | It returns True , if given element is present in list otherwise returns False. |
4 | List Iteration | It returns element of list by using for loop with list. |
Python List Built-In Methods:
Python has following built-in list methods.
Sr. | Operation | Description |
1 | list.append(object) | It appends object to the given list. |
2 | list.count(object) | It returns count of how many times object occurs in the list. |
3 | list.extend(seq) | It appends the contents of sequence to the list. |
4 | list.index(object) | It returns the lower index value of passed object in the list, if object is present in the list. |
5 | list.insert(index,object) | It inserts object into the list at offset index. |
6 | list.pop(obj=list[-1]) | It removes last object from the list and returns removed object of a list. |
7 | list.remove(object) | It removes object from the list. |
8 | list.reverse() | It reverses objects of list in place. |
9 | list.sort([func]) | It sorts objects of a list and use compare func, if given. |
Resource:
In this tutorial, you have learned how to use python lists.
Hopefully, it was clear and concise.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.
Python tutorials list:
- Python tutorials list : access all python tutorials.