A Python list is an ordered and changeable collection of data objects. Unlike an array, which can contain objects of a single type, a list can contain a mixture of objects.
As evident in the illustration above, a list can contain objects of any data type, including another list. This makes the list data structure one of the most powerful and flexible tools in Pythonic programming.
Defining a list in Python is really quite simple. The name of the list has to be specified, followed by the values it contains:
# Initiliazing a list with 5 objectsmyList1 = [20, 'Edpresso', [1, 2, 3], 3.142, None]print(myList1)# Initializing an empty listmyList2 = []print(myList2)
A list element can be accessed using its index. The index is the position of an element in the list.
Similar to other languages, Python list elements are indexed from 0
. This means that the first element will be at the 0
index.
To access an element, its index is enclosed in the []
brackets:
myIntList = [1,3,5,2,4]print(myIntList[3]) # Accessing the 4th element
The size of a list is not fixed. Elements can be added and removed at any point.
myList = ['a', 'b', 'c', 'd', 'e', 'f']# Add an element at the endmyList.append('g')print(myList)# Insert element at a specific index# insert(index, value)myList.insert(3, 'z') # Insertion at the 3rd indexprint(myList)# Delete an element from the endmyList.pop()print(myList)# Delete the value at a specific indexdel myList[1]print(myList)# Accessing the length of a listprint(len(myList))