Lists
Lists in Python are a data type that can be used to store lists of values in a single variable.
Lists are defined with square brackets [ ]
, and contain values seperated by commas ,
.
Example
chapters_covered = ["Introduction", "Statements", "Variables", "Data Types"]
Lists in Python are ordered, can be easily modified, and allow for duplicate values.
This means that items in your list will stay in the same order as you set them, and will not change unless you change them.
Indexing
Lists in Python are indexed, starting from 0
. This means that the first value in a list is at position 0
, the second value is at position 1
, and so on.
We can access the first item in a list using index [0]
, the second with [1]
, and so on.
In general, we can access the n'th item in a list with listname[n-1]
.
Example
chapters_covered = ["Introduction", "Statements", "Variables", "Data Types"]
print(chapters_covered) # ["Introduction", "Statements", "Variables", "Data Types"]
The first element has an index of 0
.
chapters_covered[0] # "Introduction"
The last element has an index of -1
.
chapters_covered[-1] # "Data Types"
You can also find the length of a list with len()
.
len(chapters_covered) # 4
You can store any data type in a list, including other lists.
You can also store different data types in the same list.
multi_type_list = ["Hello", 123, True, [1, 2, 3]]
To access lists within lists, simply add another pair of brackets [ ]
to the end of the index.
multi_type_list = ["Hello", 123, True, [1, 2, 3]]
print(multi_type_list[3][0])
Output: 1