In this tutorial, we will learn about list in Python and how to access element in a collection, this a built-in data type allow to work with multiple values.
"list" is built-in data types to store multiple elements in a single variable. We can simply create a list with a pair of brackets []
below example will help you understand more.
Example #1 - Empty List
fruits = []
To create a list with items by placing elements inside square brackets []
and separated by commas.
Example #1 - List with string items
fruits = ["Orange","Logan","Grape"]
The above example a list contain 3 items, since a list contain many items should name in plural noun. Ex: fruits, names,...
A list can hold different data types (integer, boolean, string, list, etc.).
Example #2 - List hold different type items
basket = ["Orange",3.4 ,True, 1]
A list have another list inside we called nested list
Example #3 - List hold nested items
myClass = [["Sok","Sao","John"],["Dori","Nara"]]
We can access a list item within index which is start from zero. In list the index zero base-index which is always start with 0 (Zero) located where the first element place. Let's see example below
Example #1
fruits = ["Orange","Logan","Grape","Banana"]
fruits | Orange | Logan | Grape | Banana |
Index | 0 | 1 | 2 | 3 |
List is an ordered elements and allow duplicated element. A list have 4 elements will have index start from 0 to 3. See example #2 how to access first item in list
Example #2:
fruits = ["Orange","Logan","Grape","Banana"]
print(fruits[0])
Output #2:
Orange
Increase index number to access the next item.
Example #3:
fruits = ["Orange","Logan","Grape","Banana"]
print(fruits[1])
Output #3:
Logan
IndexError
which is means found out of index range. Index is integer number only we can't use other type unless result in TypeError.
Example #4:
# Have only 4 elements. Index will have 0 to 3
fruits = ["Orange","Logan","Grape","Banana"]
# Index 0 to 3 but input 4 will produce error
print(fruits[4])
Output #4:
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(fruits[4])
IndexError: list index out of range
When I started learn Python at first place, surprisingly Python allow reverse index to access the items. The index of -1 indicated to the last element and -2 to the previous last item. See table below
fruits | Orange | Logan | Grape | Banana |
Index | 0 | 1 | 2 | 3 |
Negative Index | -4 | -3 | -2 | -1 |
Example #5:
fruits = ["Orange","Logan","Grape","Banana"]
print(fruits[-1])
Output #3:
Banana
Hope you learn and help you to understand basic how to create list and access item in Python.
PythonFounder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him