More Python Data Types
Contents
More Python Data Types#
So far, we have seen some basic data types of Python, e.g., String (str
), Integer (int
), List (list
), and Boolean (True
and False
).
Now, we are going to take a look at some additional data types.
1. Tuple#
Tuples are defined by parentheses, e.g., ()
.
Tuples are used to store multiple items in a single variable. In other words, tuple is another kind of sequence. So, you can perform indexing and slicing on tuples following the same way we discussed on lists and strings.
t = (1, 2, 3)
t[0]
1
Note
Tuple is immutable, meaning you can not change values of its elements after the tuple is defined.
The following code will produce a TypeError
as we try to modify
an element of a tuple.
t = (1, 2, 3)
t[0] = 0
1.1 Tuple unpacking#
As the example above, when we create a tuple, we normally assign values to it. This is called packing a tuple. In Python, we are also allowed to extract the values back into variables. This is called tuple unpacking which allows us to define multiple variables in one line.
a, b = (1, 2)
print(a)
print(b)
1
2
1.2 Conversion between tuple and list#
fl_city_list = ["Gainesville", "Orlando", "Tampa"]
fl_city_list
['Gainesville', 'Orlando', 'Tampa']
fl_city_tuple = tuple(fl_city_list)
fl_city_tuple
('Gainesville', 'Orlando', 'Tampa')
list(fl_city_tuple) # convert back from tuple to list
['Gainesville', 'Orlando', 'Tampa']
Note that, if we want to add another element to the end of a list, we can use
the function append
.
fl_city_list.append('Jacksonville')
fl_city_list
['Gainesville', 'Orlando', 'Tampa', 'Jacksonville']
However, since tuple is immutable, it doesn’t have this capability to add an additional element either once it’s defined.
2. Set#
Sets are defined by curly brackets, e.g., {}
.
In Python, set is uniquely indexed. Thus, there’s no duplicates in a set.
s = {1, 2, 3}
You can create a set with set
constructor.
s = set((1, 2, 3)) # (1, 2, 3) is a tuple
Similar to list, we can mix multiple data types in a set.
mixed_set = {'URP', 6271, True}
Warning
Since set is unordered, unlike other “collections” of Python,
e.g., list, string, tuple, set is not subscripable, meaning we can’t
perform indexing and slicing on it.
The following codes will produce an TypeError
, as we attempt to grab the
first element of the set.
s = {1, 2, 3}
s[0]
more_cities = ['Gainesville', 'Tampa', 'Fort Myers',
'St. Augustine', 'Orlando']
for fl_city in more_cities:
fl_city_list.append(fl_city)
print(fl_city_list)
['Gainesville', 'Orlando', 'Tampa', 'Jacksonville', 'Gainesville']
['Gainesville', 'Orlando', 'Tampa', 'Jacksonville', 'Gainesville', 'Tampa']
['Gainesville', 'Orlando', 'Tampa', 'Jacksonville', 'Gainesville', 'Tampa', 'Fort Myers']
['Gainesville', 'Orlando', 'Tampa', 'Jacksonville', 'Gainesville', 'Tampa', 'Fort Myers', 'St. Augustine']
['Gainesville', 'Orlando', 'Tampa', 'Jacksonville', 'Gainesville', 'Tampa', 'Fort Myers', 'St. Augustine', 'Orlando']
set(fl_city_list)
{'Fort Myers',
'Gainesville',
'Jacksonville',
'Orlando',
'St. Augustine',
'Tampa'}
for city in set(fl_city_list):
print('I like ' + city)
I like Tampa
I like St. Augustine
I like Jacksonville
I like Gainesville
I like Orlando
I like Fort Myers
3. Dictionary#
Consists of a collection of {<key>: <value>}
pairs wrapped around by curly brackets.
my_dict = {'institution': 'University of Florida',
'college': 'Design, Construction, and Planning',
'enrollment year': 2023,
'graduate': True}
my_dict
{'institution': 'University of Florida',
'college': 'Design, Construction, and Planning',
'enrollment year': 2023,
'graduate': True}
3.1 Indexing on Dictionary#
You can access a dictionary’s value(s) by its corresponding key(s).
print(my_dict['college'])
Design, Construction, and Planning
Warning
For dictionaries, you cannot use positional index.
my_dict[0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15588\2056869115.py in <cell line: 1>()
----> 1 my_dict[0]
KeyError: 0
3.2 Keys and values#
The keys()
and values()
functions return an iterable of all keys and values.
Therefore, you can iterate over them using a for
loop.
my_dict.keys()
dict_keys(['institution', 'college', 'enrollment year', 'graduate'])
my_dict.values()
dict_values(['University of Florida', 'Design, Construction, and Planning', 2023, True])
for key in my_dict.keys():
print(my_dict[key])
University of Florida
Design, Construction, and Planning
2023
True
The items()
return a tuple of (<key>, <value>)
pair.
We can use tuple unpacking technique to assign values to two variables at the same time.
for key, value in my_dict.items():
print('the value of ' + key + 'is ' + value) # what's wrong here
the value of institutionis University of Florida
the value of collegeis Design, Construction, and Planning
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15588\2290443898.py in <cell line: 1>()
1 for key, value in my_dict.items():
----> 2 print('the value of ' + key + 'is ' + value) # what's wrong here
TypeError: can only concatenate str (not "int") to str
3.3 Dictionary with values of list#
Note how we can access elements of individual lists.
city_dict = {"FL": ["Gainesville", "Orlando", "Tampa"],
"CA": ["San Francisco", "Los Angeles"],
"TA": ["Houston", "San Antonio"]}
city_dict['FL'][0]
'Gainesville'
4. String format()
function#
The format()
function is capable of handling complex string formatting more efficiently.
Sometimes we want to make generalized print statements or string definitions
in that case instead of writing it differently every time we use the concept of formatting.
print("I'm from the College of {} at the {}.".format(
my_dict["college"], my_dict["institution"])
)
I'm from the College of Design, Construction, and Planning at the University of Florida.
for key, value in my_dict.items():
print('the value of {} is {}'.format(key, value)) # what is the problem and how to fix it
the value of institution is University of Florida
the value of college is Design, Construction, and Planning
the value of enrollment year is 2023
the value of graduate is True
for key, value in my_dict.items():
print('the value of {} is {}'.format(key.upper(), value)) # what is the problem and how to fix it
the value of INSTITUTION is University of Florida
the value of COLLEGE is Design, Construction, and Planning
the value of ENROLLMENT YEAR is 2023
the value of GRADUATE is True
5. List comprehension#
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. You can also use it to very neatly iterate through a list.
[print(city) for city in fl_city_list]
Gainesville
Orlando
Tampa
Jacksonville
Gainesville
Tampa
Fort Myers
St. Augustine
Orlando
[None, None, None, None, None, None, None, None, None]
x = [1, 2, 3, 4]
out = []
for item in x:
out.append(item**2)
print(out)
[1, 4, 9, 16]
[item**2 for item in x]
[1, 4, 9, 16]