Python comes with built-in container objects. These objects store data and are also iterable
, meaning there is a mechanism to iterate through the values stored in the container.
Lists are a fundamental data structure in Python. They are used to store heterogeneous data and are created with a pair of square brackets, [ ]
.
my_list = ['a', 1, True, 3.14]
print(my_list)
['a', 1, True, 3.14]
We can subset the list using square brackets and provide the index of the item we want.
# get the first item - index 0
print(my_list[0])
a
We can also pass in a range of values (Appendix P).
# get the first 3 values
print(my_list[:3])
['a', 1, True]
We can reassign values when we subset values from the list.
# reassign the first value
my_list[0] = 'zzzzz'
print(my_list)
['zzzzz', 1, True, 3.14]
Lists are objects in Python (Appendix S), so they will have methods that they can perform. For example, we can .append()
values to the list.
my_list.append('appended a new value!')
print(my_list)
['zzzzz', 1, True, 3.14, 'appended a new value!']
More about lists and their various methods can be found in the documentation.1
1. https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
A tuple
is similar to a list
, in that both can hold heterogeneous bits of information. The main difference is that the contents of a tuple are “immutable”, meaning they cannot be changed. They are created with a pair of round parentheses, ( )
.
my_tuple =('a', 1, True, 3.14)
print(my_tuple)
('a', 1, True, 3.14)
Subsetting items can be accomplished in the same ways as for a list (i.e., you use square brackets).
# get the first item
print(my_tuple[0])
a
However, if we try to change the contents of an index, we will get an error.
# this will cause an error
my_tuple[0] = 'zzzzz'
TypeError: 'tuple' object does not support item assignment
More information about tuples can be found in the documentation.2
2. https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
Python dictionaries (dict
) are efficient ways of storing information. Just as an actual dictionary stores a word and its corresponding definition, a Python dict
stores some key and a corresponding value. Using dictionaries can make your code more readable because a label is assigned to each value in the dictionary. Contrast this with list
objects, which are unlabeled. Dictionaries are created by using a set of curly braces, { }
.
my_dict = {}
print(my_dict)
{}
print(type(my_dict))
<class 'dict'>
When we have a dict
, we can add values to it by using square brackets, [ ]
. We put the key inside these square brackets. Usually, it is some string, but it can actually be any immutable type (e.g., a Python tuple
, which is the immutable form of a Python list
). Here we create two keys, fname
and lname
, for a first name and last name, respectively.
my_dict['fname'] = 'Daniel'
my_dict['lname'] = 'Chen'
We can also create a dictionary directly, with key–value pairs instead of adding them one at a time. To do this, we use our curly braces, { }
, with the key–value pairs being specified by a colon.
my_dict = {'fname': 'Daniel', 'lname': 'Chen'}
print(my_dict)
{'fname': 'Daniel', 'lname': 'Chen'}
To get the values from our keys, we can use the square brackets with the key inside.
fn = my_dict['fname']
print(fn)
Daniel
We can also use the .get()
method.
ln = my_dict.get('lname')
print(ln)
Chen
The main difference between these two ways of getting the values from the dictionary is the behavior that occurs when you try to get a nonexistent key. When using the square-bracket notation, trying to get a key that does not exist will return an error.
# will return an error
print(my_dict['age'])
KeyError: 'age'
In contrast, the .get()
method will return None
.
# will return None
print(my_dict.get('age'))
None
To get all the keys
from the dict
, we can use the .keys()
method.
# get all the keys in the dictionary
print(my_dict.keys())
dict_keys(['fname', 'lname'])
To get all the values
from the dict
, we can use the .values()
method.
# get all the values in the dictionary
print(my_dict.values())
dict_values(['Daniel', 'Chen'])
To get every key–value pair, you can use the .items()
method. This can be useful if you need to loop through a dictionary.
print(my_dict.items())
dict_items([('fname', 'Daniel'), ('lname', 'Chen')])
Each key–value pair is returned in a form of a tuple
, as indicated by the use of round parentheses, ( )
.
More on dictionaries can be found in the official documentation on data structures.3
3. https://docs.python.org/3/tutorial/datastructures.html#dictionaries
3.16.218.221