Lists and Dictionaries are kind of like super variables. They allow you to store multiple data under a singular name. In the example below, I first assign the variable ‘a‘ a value of 6. Next when I go to assign it a value of 7, it replaces 6.
What if I want to keep both 6 and 7?
Sure I could use 2 variables, (ex. a and b), or I can use a list.
List
A list is a collection of data in Python. You create a list by assigning a variable a group of data enclosed in square brackets [].
Notice that lists are indexed, meaning you call them up using the following syntax: variable[index]
Note that indexes in Python start at 0. So in our set of 4 elements, the indexes would be 0,1,2,3. Notice when I try to use index 4, I get an out of range error.
Lists can also hold strings, or combinations of values in one list.
Try your code in our online Python console:
Adding and removing elements from a list
.append(): adds a element to the list
.pop(): removes last element from list
.remove(value): removes element matching value
del list[index]: deletes element by index
.clear(): removes all elements
Try your code in our online Python console:
Dictionaries
This of dictionaries as lists with named indexes. This makes looking up values easier (especially when your code get more complicated).
Each data element is paired with a named index. A dictionary is denoted through the use of curly braces {} and : separating the named index and the value.
Try your code in our online Python console:
If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT.
Last Page: Printing with .format{}
Next Page: Working with lists
Back to Python Course: Course