We know that variables are a useful way to store individual pieces of data, but what if we want to store a collection of data? For example, a playlist is a collection of songs. A shopping cart is a collection of items. In Python, we can represent a collection of data in a list.
Creating a list in Python is very similar to declaring a variable. Here are a few example lists.
shopping_list = ['Milk', 'Eggs', 'Bread']
scores = [80, 55, 62, 100]
info = [32, 'tall', True]
leds = [L0, L1, L2, L3, L4, L5]
Notice that lists can contain strings, numbers, Boolean values, objects, or any combination of those things. Lists follow the same naming conventions as variables. A complete list is surrounded by square brackets [ ] , and individual items are separated by commas , The items in a list are often called elements.
We can also create empty lists, which we can add elements to later. To declare an empty list, leave the brackets empty like so:
empty_list = []
Python has some built-in functions that can be used with lists.
Back in our functions lesson, we learned that len() returns the length of a string. It can also be used to count the number of elements in a list!
a = len(['a', 'b', 'b']) # a = 3
b = len([]) # b = 0
sum() takes a list of numbers as an input, and returns the sum of all of the numbers in the list.
a = sum([1,2,3]) # a = 6
b = sum([1, 1.5]) # b = 2.5
c = sum([5, -4, -3]) # c = -2
One of the most useful things about lists is that they store elements in a particular order. To keep track of which element is at which position in the list, every element has an index, or a number that represents its position in the list.
In most programming languages, we start counting from 0, so the first element in the list will have the index 0, the second element will have the index 1 and so on.
list = [element_0, element_1, element_2, ..., element_n]
# indices: 0 1 2 ... n
To access a particular element of a list, we use square brackets []
alphabet = ['a', 'b', 'c', 'd']
print(alphabet[2]) # this will print 'c'
We can also use indexing to change a particular element in a list.
alphabet[0] = 'Q' # alphabet = ['Q', 'b', 'c', 'd']