Python Lists
Python List
Python List is an ordered collection of items.
list is the class name for List datatype in Python. To define a list in Python, you can use square brackets or list() inbuilt function.
list1 = [4, 8, 7, 6, 9]
list2 = list([4, 8, 7, 6, 9])
Datatype of Items in a List
Items in a list can be of any datatype. It could be any of the inbuilt datatypes: int, float, list, dict, str, etc., or user defined datatype.
In the following example, we will define a list with different datatypes.
Python Program
list1 = ["Apple", 54, 87.36, True]
print(list1)
Output
['Apple', 54, 87.36, True]
Access Items
Python List is an ordered collection of items. So, you can access a specific element using index.
Index of first item is 0, the second is 1, third is 2, and so on.
In the following example, we will define a list with some items and access the elements using index.
Python Program
list1 = ["Apple", 54, 87.36, True]
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
Output
Apple
54
87.36
True
Update Items
You can update items in Python List with new values using index and assignment operator.
The syntax to update items in Python list is
list[index] = new_value
In the following example, we will take a list with some items, and update the item at index 2.
Python Program
list1 = ['apple', 'banana', 'cherry', 'fig']
list1[2] = 'orange'
print(list1)
Output
['apple', 'banana', 'orange', 'fig']
List Operations
Similar to how we have accessed or updated Python Lists, you can perform many operations on lists and their elements. For complete list of operations on Python Lists, follow Python List Operations tutorial.
Python List Methods
The following are the methods of list data type. You can call these methods on list type objects. Each of the following tutorial gives the syntax and usage of the respective method with examples.
Summary
In this tutorial of Python Examples, we learned about Python List, and got hands on Python Lists to create them, access the elements and update the elements of Lists.