Lesson 5: Data Structures: Lists, Dictionaries and Tuples

Learning data structures is one of the first steps to start accumulating data and write more complex programs. Below we will see some examples to clarify main data structure concepts, how to assign data to them and how to initiate them with the functions mentioned in this lesson.

In this lesson you will also learn different data structures in Python such as lists, dictionaries and tuples. You will also have an idea of which Python data structure to use with which type of data in future.

In the next lessons we will also introduce specific methods regarding Python data structures such as List Methods, Dictionary Methods and Tuple Methods.

We will initiate following data structures with respective characters in front of them below:

list : []
tuple : ()
dictionary : {}

Used Where?

We couldn’t do justice to data structures if we listed 100 use cases here.

Data structures can vary from anything like: 

  • Low-level computer language commands to a video game’s characters
  • Meteorological forecast to someone’s shopping list
  • A Python function’s parameters to World Bank Import Export data.

Basically data structures consist of other collections such as lists, dictionaries and tuples or more simple data types such as integers, floats and strings.

Syntax do(s)

1) list(), dict() and float() all have parenthesis after them because they are functions.

Syntax don't(s)

1) () alone represents tuple parenthesis and shouldn't be confused with parenthesis in function list() etc.

2) When creating an empty list, you need to use brackets and not parenthesis: []

Python Lists

Data structures are needed in all aspects of programming.
  • Lists: Contains values. It can be pretty much anything, numbers, strings, names, features etc. i.e.:
    • models of your cars,
    • names of your dogs,
    • countries you have visited,
    • customers that shopped at your store.
list() and dict() functions are very simple and straightforward. They help you create either lists or dictionaries.

Function 1: list()

In this lesson we will use list() function which has a very simple implementation and usage.

Example 1

>>> my_first_list = []
>>> print(my_first_list )
>>> print(type(my_first_list ))

[]
<class ‘list’>

You can see how we create a list simply using brackets. Then when we print this variable with an empty list assigned to it we get [] representing that our variable is a list, but it’s empty. And when we print its type we get a class ‘list’ message.

And in this example we can replicate the identical outcome as the first example, this time using list() function.

Example 2

>>> my_first_list = list()
>>> print(my_first_list)
>>> print(type(my_first_list))

[]
<class ‘list’>

Python Dictionaries

  • Dictionaries: Dictionaries are key-value pairs. So a dictionary consists of two parts: keys and values. Unlike tuples and like lists, dictionaries are mutable, meaning their values can be changed, replaced and removed. They are great data structures when you need to save a value with its features. i.e.:
    • your client data including clients’ names and their purchase values
    • country names with amounts of Olympic medals they won
    • car brands with models they offer
    • countries with their fatal traffic accident numbers per year. etc.

Function 2: dict()

We will also cover dict() function which helps you create a Python dictionary.

And here is a similar example for an empty dictionary assignment.

Example 3

>>> my_first_dictionary = {}
>>> print(my_first_dictionary)
>>> print(type(my_first_dictionary))

{}
<class ‘dict’>

And in this example we can replicate the identical outcome as the first example, this time using dict() function.

Example 4

>>> my_first_dictionary = dict()
>>> print(my_first_dictionary)
>>> print(type(my_first_dictionary))

{}
<class ‘dict’>

Python Tuples

  • Tuples: Tuples resemble lists very much however there is a catch. Once you create a tuple, unlike a list, you can’t change its values. In Python, fancy name for this is “mutability“. So while lists are mutable, tuples are immutable, meaning they can’t be changed after creation. You may think, why would I need that? There are cases when you may prefer that extra security layer of unchangeability. As programs become complex and start making lots of iterations and collections etc. Write-off protection that tuples offer can be handy. i.e.:
    • months of a year, sports in Olympic,
    • counties in the United States.

Note though, this doesn’t mean a tuple can never ever be changed. You can simply alter your code where you create your tuple and add, remove, replace values. Mutability rather means its values can not be changed after creation, during the execution of the rest of your program.

Function 3: tuple()

We will also cover tuple() function which helps you create a Python tuple.

And here is an example for an empty tuple assignment.

Example 5

>>> my_first_tuple = ()
>>> print(my_first_tuple)
>>> print(type(my_first_tuple))

()
<class ‘tuple’>

And in this example we can replicate the identical outcome as the first example, this time using dict() function.

Example 6

>>> my_first_tuple = tuple()
>>> print(my_first_tuple)
>>> print(type(my_first_tuple))

()
<class ‘tuple’>

Tips

  1. You can initiate a list, tuple or dictionary variable in numerous ways. One of the most common is simply assigning the appropriate symbols to the variables. Appropriate symbol for list is square brackets: [] , for tuples, parenthesis: () and for dictionaries, curly brackets: {}. If you just assign this symbols without any data in between Python will understand that you are trying to create the related data structure.
  2. Tuples are ideal alternatives to lists when you don’t want to change the values of the data structure later on.
  3. Dictionary is an ideal structure to hold key-value pairs.

Let’s create a list that’s not empty this time and with values in it.

Example 7

>>> mylist = [“ski boots”, “skis”, “gloves”]
>>> print(mylist)
>>> print(type(mylist))

[‘ski boots’, ‘skis’, ‘gloves’]
<class ‘list’>

In this example, our list happens to be consisted of 3 string values. But as lists, dictionaries and tuples are composite data structures, they can be consisted of multiple data types.

Now let’s create a dictionary example with values.

Example 8

>>> mydict = {“ski boots”: 3, “skis”: 2, “gloves”: 5}
>>> print(mydict)
>>> print(type(mydict))

{‘ski boots’: 3, ‘skis’: 2, ‘gloves’: 5}
<class ‘dict’>

In this example, we create a dictionary and assigned it to the variable mydict. mydict consists of 3 keys: “ski boots”, “skis” and “gloves” and each key has one value assigned to it. These values are: 3, 4 and 5.

Now let’s create a list example with multiple data types in it.

Example 9

>>> mylist = [“carabiners”, False, “chalk powder”, 666, 25.25]
>>> print(mylist)
>>> print(type(mylist))

[“carabiners”, “sunglasses”, “chalk powder”, 666, 25.25]
<class ‘list’>

As you can see, here we have 4 types of different data values in one list:
These are (in order): string, boolean, string, integer and float.

Finally, let’s create a tuple example.

Example 10

>>> mytuple = (“carabiners”, False, “chalk powder”, 666, 25.25)
>>> print(mytuple)
>>> print(type(mytuple))

(“carabiners”, “sunglasses”, “chalk powder”, 666, 25.25)
<class ‘tuple’>

The only difference here, compared to example 9, is that we are using parenthesis (), instead of brackets [], hence creating a tuple instead of a list. In the upcoming classes you will see that list will be more convenient to change its values after it’s created and tuple won’t allow such operations.

Advanced Concepts (Optional)

1- In Python, each data structure has its own built-in functions.

2- We will take a look at some of the most common methods in the next lessons. Also some of them will be their own lessons as they need more elaboration.

3- Here are some examples:

  • Strings:
    • .lower()
    • .upper()
    • .capitalize()
    • .startswith()
    • .endswith()
    • .join()
    • .split()
    • .strip()
    • .index()
    • .count()
    • .find()
    • .min()
    • .max()
    • .replace()
    • len()
    • type()
  • Lists:
    • .append()
    • .insert()
    • .pop()
    • .remove()
    • .replace()
    • .index()
    • .count()
    • .sum()
    • .reverse()
    • .clear()
    • .min()
    • .max()
    • len()
  • Dictionaries:
    • .clear()
    • .copy()
    • .keys()
    • .items()
    • .get()
    • len()
    • type()
  • Tuples:
    • .count()
    • .sum()
    • .min()
    • .max()
    • len()
    • type()

Footnotes: 

* You may realize some of the methods above have dots in front of them and others don’t. It can be useful to explain this to avoid confusion in the future.

** The ones with dots are called on your object and take parameters inside and the ones without dots are rather standalone functions. This will become more clear later. 

How can I print Python collections such as lists, tuples and dictionaries vertically?

Sometimes you may want to print your lists in most comprehensible way on the go to be able to understand, interpret and make use of your data.

While this can easily be achieved using a simple for loop, we will also share a classy trick that was inspired by 39th point in this Python tips post: unpacking Python lists with star notation.

Let’s check out the more “traditional” way first:

Example 11: Printing lists vertically

  • Let’s take a look at a list which consists of the column names of a random dataset. You can see items are in string format and it’s pretty confusing and hard to read in this format.
lst = ['Unnamed: 0', 'id', 'date', 'price', 'bedrooms', 'bathrooms', 
'sqft_living', 'sqft_lot', 'floors', 'waterfront', 'view', 'condition', 
'year_built', 'year_renovated', 'zipcode']

print(lst)

[‘Unnamed: 0’, ‘id’, ‘date’, ‘price’, ‘bedrooms’, ‘bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘waterfront’, ‘view’, ‘condition’, ‘year_built’, ‘year_renovated’, ‘zipcode’]

  • Okay, here is a simple  for loop which will print lists vertically for you.
  • Here is anorher lesson if you need a refresher on Python For Loops.
lst = ['Unnamed: 0', 'id', 'date', 'price', 'bedrooms', 'bathrooms', 
'sqft_living', 'sqft_lot', 'floors', 'waterfront', 'view', 'condition', 
'year_built', 'year_renovated', 'zipcode']

for i in lst:
    print(i)

Unnamed: 0
id
date
price
bedrooms
bathrooms
sqft_living
sqft_lot
floors
waterfront
view
condition
year_built
year_renovated
zipcode

Example 12: Printing lists vertically in one line

  • This method can get the same job of printing a Python list’s items vertically in a much more Pythonic way in one line.
lst = ['Unnamed: 0', 'id', 'date', 'price', 'bedrooms', 'bathrooms', 
'sqft_living', 'sqft_lot', 'floors', 'waterfront', 'view', 'condition', 
'year_built', 'year_renovated', 'zipcode']

print(*lst, sep="\n")

Unnamed: 0
id
date
price
bedrooms
bathrooms
sqft_living
sqft_lot
floors
waterfront
view
condition
year_built
year_renovated
zipcode

  • With this method you don’t have to bother with constructing a  for loop which can be tedious when you need a quick on the go solution.
  • What’s happening here is that we are using star (or asterisk) notation to unpack the list. Star is used to unpack collections such as lists and tuples and feed each element to a function. We are feeding unpacked list to print function here.
  • Then we are using sep parameter which is used in Python print function to separate each item being printed with a specific character. Since “\n” is the character for “new line” each item is printed in a new line.

Example 13: Printing lists vertically with enumerate

  • Here is another example. Enumerate function and vertical printing all in just one line.
  • Enumerate function is another useful Python function that can be used to give numbers to each list item or “enumerate” it.
lst = ["libor", "gold", "treasury_bond", "stock_options"]

print(enumerate(*lst, 100), sep="\n")

(100, ‘libor’)
(101, ‘gold’)
(102, ‘treasury_bond’)
(103, ‘stock_options’)

  • Normally  enumerate function starts counting from 0 by default, so we are also passing a value to its second parameter so it starts counting from 100.

Next Lesson: Python Lists

“Have you installed Python yet?”
Having Python setup on your computer can expedite the learning experience and help you gain the real life skills in a non-simulation environment. Installing Python can have different nuances that can be confusing for everyone. We compiled a complete tutorial about the best and most convenient Python installing practices Check it out by clicking the button below.
SANDRA FILES