Introduction
In this article, I’m going to show you how to create a list in Python and how to access its elements through positive and negative indexing. And we will also learn about the main characteristics of a Python list.
What is a Python List?
In Python, a list is a dynamically sized array that stores multiple items of various data types in a single container.
How to Create a List in Python?
We can create a list by putting any number of comma-separated values between square brackets. To create an empty list, use a blank pair of square brackets.
# An empty list. empty_list = []
Lists can contain any number of elements, and those elements can all be the same type.
# List of integers. integers_list = [1, 2, 3] # List of strings. strings_list = ['red', 'green', 'blue', 'blue'] # List of booleans. booleans_list = [True, False, True]
But, they do not have to be of the same type. A single list may contain different data types like integers, strings, booleans, etc. It can also have another list as an item, and this is called a nested list.
# List of mixed data types. mixed_list = [36, 'blue', True, [1, 4, 9, 16]]
Access List Items
Positive Indexing
List items are indexed, and the indexing starts from 0, moving from left to right. So the second item of the list has index one, not two. Here we will use the “index” method to find the index of the second item of the “mixed_list”.
mixed_list = [36, 'blue', True, [1, 4, 9, 16]] # Find the index of the second item. second_item_index = mixed_list.index('blue') print('Second item index: {}'.format(second_item_index)) # Output: Second item index: 1
To access values in lists, use the square brackets with the item index to obtain the value at that index. For example, here, we want to access the third item of the “mixed_list”.
mixed_list = [36, 'blue', True, [1, 4, 9, 16]] # Obtain the value of the third item of the list. third_item = mixed_list[2] print('Third item is: {}'.format(third_item)) # Output: Third item is: True
Referring to an index that does not exist will generate an “IndexError” exception.
strings_list = ['red', 'green', 'blue', 'blue'] # There is no item at index number 4. try: fifth_item = strings_list[4] except IndexError as ex: print(ex) # Output: list index out of range
Item index must be an integer. Using other types as an index will cause a “TypeError” exception.
strings_list = ['red', 'green', 'blue', 'blue'] # Item index must be an integer. try: third_item = strings_list[2.5] except TypeError as ex: print(ex) # Output: list indices must be integers or slices, not float
Negative Indexing
We can also use negative indexing to refer to list items from the end. For example, the -1 index refers to the last element of the list, and -2 refers to the second last.
strings_list = ['red', 'green', 'blue', 'blue'] # Obtain the value of the last item. last_item = strings_list[-1] print('Last item is: {}'.format(last_item)) # Output: Last item is: blue
And finally, to access a nested list, append an additional index.
mixed_list = [36, 'blue', True, [1, 4, 9, 16]] # Access to the second item of the nested list. nested_list_second_item = mixed_list[3][1] print('Second item of the nested list is: {}'.format(nested_list_second_item)) # Output: Second item of the nested list is: 4
Allow Duplicate Items
Since Python lists are indexed, they can store multiple items with the same value. Here, we will find how many elements with the value of “blue” exist in our list using the “count” method.
strings_list = ['red', 'green', 'blue', 'blue'] duplicate_values = strings_list.count('blue') print('Number of items with value of "blue": {}'.format(duplicate_values)) # Output: Number of items with value of "blue": 2
Lists are Mutable
Lists in Python are mutable, which means we can add, remove and update their elements, unlike a tuple. To change the value of a list item, we can refer to it using its index and then assign it with the new value.
mixed_list = [36, 'blue', True, [1, 4, 9, 16]] print('Before: {}'.format(mixed_list)) # Output: Before: [36, 'blue', True, [1, 4, 9, 16]] # Change the value of the second last item to False. mixed_list[-2] = False print('After: {}'.format(mixed_list)) # Output: After: [36, 'blue', False, [1, 4, 9, 16]]
Lists are Ordered
Lists items have a defined order, and two lists with the same elements in different order are not equal.
# Two lists with the same elements but in a different order. list1 = [1, 2, 3, 4] list2 = [2, 3, 4, 1] if list1 == list2: print('They are equal.') else: print("They aren't equal.") # Output: They aren't equal.
GitHub Repo
Here is the GitHub repository where you can find the complete source code of this article, clone the project and run it on your machine.