Lists
tags: #python/documentation/data_structures/lists
What is a List?
In Python, a list is a built-in data structure that allows you to store and organize a collection of items (or elements).
How are elements stored in a list?
Elements are stored in sequential order, where each element can be identified by an index corresponding to the relative position in the list, and are separated by a comma.
- Can contain a combination of different data types (this is referred to as a compound list; this should be avoided when creating lists)
- Elements are mutable - i.e., you can modify them by adding, removing, or changing the elements.
- Allows for duplicates
Creating a List in Python
A Python List can be created by enclosing a sequence of elements, separated by commas, in [], and assigning it to a variable name using the assignment operator:
# Example of an empty list
empty_list = []
# Creating a list of the same data type
numbers = [1, 2, 3, 4, 5]
text = ['apple', 'banana', 'orange']
# Creating a list of different data types
compound_list = [1, 'apple', 3.14, True]
Creating an empty list
You can create an empty list with empty square brackets ([]) and assigning it to a variable:
empty_lst = []
Retrieving Elements in a List
Recall Python uses zero-indexing. Therefore, elements in a Python list can be retrieved using there zero-indexing position, where the first element in the List is 0.
Zero-indexing is a system of numbering items in a sequence, such as elements in an array, list, or string, where the first item is assigned the index of 0.
Indexing a Python List
Elements in a list can be retrieved by indexing by using the index operator ([ ]):
# 0 1 2
fruits = ['apple', 'banana', 'orange']
# indexing for banana
>>> print(fruits[1])
'banana'