Lesson 5: Data Structures

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.

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.

Upcoming example will demonstrate this very easily but in short the symbols are as below:

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

And the functions that we will demonstrate in this page are simply alternative ways to initiate lists, tuples or dictionaries. It’s not crucial to know but depending on your taste you might want to use them and it’s good to be aware of them to avoid confusion in case they are used by another programmer.

Function 1: list()

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

Used Where?

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.
  • 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. 

  • 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.
  • list() and dict() functions are very simple and straightforward. They help you create either lists or dictionaries.

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: []

You can see below 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.

Example 1

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

[]
<class ‘list’>

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’>

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’>

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- Tuples are ideal alternatives to lists when you don’t want to change the values of the data structure later on.

2- 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. 

Exercise 5

Lesson 6

Lists

winslow homer gulf streamad


Winslow Homer

The Gulf Stream

The Gulf Stream by Winslow Homer

“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