Python Lists
Python Lists
Python Lists
Python Lists
Python List is an ordered collection of elements and you can store objects of any datatype in the list.
As Python List is an ordered collection, you can access the elements using index (position of the element in the
element). Like in other programming languages like Java, C, C++, etc, the index starts from 0 until the
number of items in the list.
Python List
elements 2 5 8 11 14 17
index 0 1 2 3 4 5
www.tutorialkart.com
aList = list()
aList = []
In addition, let us find out datatype of the variable aList programmatically using type() function.
Python Program
Run the program, and Python interpreter shall print the datatype of aList to standard output.
Output
<class 'list'>
element = aList[index]
We already know that index starts from 0 . Therefore, aList[0] fetches first element of the list and aList[5]
fetches 6th element in the list.
Python Program
element = aList[2]
print(element)
element = aList[4]
print(element)
Output
541
True
aList[2] returns third element of the list and aList[4] returns fifth element of the list.
aList[index] = new_value
In the following program, we shall modify the element present at the index 2.
Python Program
aList[2] = 'mango'
Output
apple
banana
mango
orange
papaya
element in aList
The above expression returns a boolean value. True if element is present in the list and false if not.
Python Program
element = 'banana'
if element in aList:
print('The element is present in list.')
else:
print('The element is not present in list.')
Output
Python Program
Output
Python Program
aList = [21, 53, 84]
aList.append(96)
print(aList)
Output
Python Program
aList.insert(2, 'mango')
Output
apple
banana
mango
cherry
In the following is a program, we will use Python For loop to iterate over list. We are just printing the element,
buy you may write multiple statement to process or transform the list element.
Python Program
Output
21
53
84
In the following is a program, we will use Python While loop to iterate over list.
Python Program
index = 0
while index < len(aList):
print(aList[index])
index += 1
Output
21
53
84
In the following program, we will sort the list of numbers in ascending order.
Python Program
aList.sort()
Output
5
21
53
62
84
In the following program, we will sort the list of numbers in descending order.
Python Program
aList.sort(reverse=True)
84
62
53
21
5
Conclusion
In this Python Tutorial, we learned about List in Python programming, how to access its elements and some of
the operations that can be performed on a List.
Python Programming
⊩ Python Tutorial
⊩ Install Python
⊩ Python Variables
⊩ Python Comments
Control Statements
⊩ Python If
⊩ Python If Else
Python String
Functions
⊩ Python Functions
Python Collections
⊩ Python List
⊩ Python Dictionary
Advanced
⊩ Python Multithreading
Useful Resources