DEV Community

Cover image for Part Three: Data Structures
Simon Chalder
Simon Chalder

Posted on • Updated on

Part Three: Data Structures

Welcome to part three. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at some of the ways we can store multiple values in a single variable in Python, but first let's take a look at the solution for the challenges set in part two.


β€œFailure is the condiment that gives success its flavour.” – Truman Capote


Solution to part two's challenges


Task 1

1. 40
2. 336
3. -84
4. 15
5. # Python knows BIDMAS rules so we can solve this with either:
num2 + num1 * num3 / (num1 - num2)

# Or we can use brackets to seperate the multiplication and division from the addition and subtraction
num2 + (num1 * num3) / (num1 - num2)

Answer: 30.25 (result is a float)
Enter fullscreen mode Exit fullscreen mode

Task 2

animal = "Crayfish"
plant = "Honeysuckle"
habitat = "woodland"

1. answer = animal[0]
'C'
2. answer = habitat[-1]
't'
3. answer = animal[4:8] OR animal[4:] OR animal[-4:]
'fish'
4. answer = plant[0:5] OR plant[:5]
5. answer = habitat[-4:8] OR habitat[-4:]
Enter fullscreen mode Exit fullscreen mode

Data Structures


Why do we care about data structures?

Data structures allow us to store data in an organised manner so that it can later be retrieved easily. Examples of data structures in coding projects include:

  • The basket containing order items in an online store

  • Creating a list of customers and performing an action for each customer such as sending an email

  • Collect survey or study results in a list so as to be able to easily visualise or export your results


So far we have looked at using variables to contain a single value. However, we are also able to store multiple values in a single variable. Python offers 3 flavours for this, the first of which is the list. Lists can store any number of items and accept all data types so mixed type lists are possible.


Lists


"I love the way a list makes a big hodgepodge of things simmer down and behave." - Blue Balliett


A list is a way to store multiple values in a single variable. Theoretically there is a limit to the number of values or items we can store in a Python list, this source suggests 536,870,912 but in practical terms, let's just say they can hold more items than you will ever reasonably need to worry about. So what can we put in our lists? Well for starters:

  • Integers

  • Strings

  • Floats

  • Boolean

  • Other lists (yes lists within lists!)

We can mix and match our data types to create lists with all manner of items together in the same variable.

We can create a list by giving it a name just like a variable and then after our '=' sign we tell Python this is a list using '[]' square brackets. We can create an empty list by just using empty square brackets or we can add items when we create the list. Our list items go between the square brackets and are separated by a comma.

my_empty_list = []

list_of_biomes = ["tundra", "arctic", "jungle", "desert"]

random_list = ["orange", 33, "blue", False, 6.85]
Enter fullscreen mode Exit fullscreen mode

Lists operate in much the same way as strings. Whereas strings assign an index to each character, a list assigns an index to each list item. In the following example we create a list in IDLE named mammals and use it to store some string values.

mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
Enter fullscreen mode Exit fullscreen mode

We can now access values in the list in the same way we sliced characters in a string using the index number. Just like strings, items in a list start at index 0.

animal = mammals[1]
print(animal)
Hare
Enter fullscreen mode Exit fullscreen mode

Each of these items in our list is a string and as such we can delve deeper into the list, extracting string characters from list items. To do this we use 2 sets of square brackets, the first determining the list item and the second the character in the string

In this example we slice the 4th character of the first string item.

mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
letter = mammals[0][4]
S
Enter fullscreen mode Exit fullscreen mode

Lists can also contain other lists. In this next example, the 4th item in my_list is another list of integers. Placing lists within lists is known as 'nesting'.

my_list = [2, 4, 6, [3, 5, 7,], 8]
Enter fullscreen mode Exit fullscreen mode

To access a value in the nested list we once again use 2 sets of square brackets. Just like with getting individual characters from list items, the first bracket contains the index of the list item. The second brackets contain the index of the nested list's item.
For example, if we wanted the 2nd character of the nested list (located at item 4 in my_list) we would use the following:

nested_character = my_list[3, 1]
print(nested_character)
5
Enter fullscreen mode Exit fullscreen mode

OK, great but what if we want to change our list by changing, adding or removing items?

To change an item in a list, we assign a value in much the same way as declaring a variable.

mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
mammals[1] = "Osprey"
print(mammals)
['Red Squirrel', 'Osprey', 'Barn Owl', 'Pine Marten']
Enter fullscreen mode Exit fullscreen mode

In the above example, the 2nd item in the list is changed from "Hare" to "Osprey".

We can also change several items at once. In this next example we change the 3rd and 4th items to different items.

mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
mammals[2:4] = ["Elephant", "Tiger"]
print(mammals)
['Red Squirrel', 'Osprey', 'Elephant', 'Tiger']

Enter fullscreen mode Exit fullscreen mode

A brief and passing introduction to methods


Whoa, hang on there! What's this method thing you're trying to sneak in?

We will get into functions and methods in the future but for now just know that a method is a chunk of pre-written code built into Python that performs a certain repeatable action. We have actually already been using one of Python's built in methods. Remember the print() code we wrote to show the contents of our variable? The print method came with Python so we did not have to figure out how to get our output onto the screen from scratch. Methods are huge time savers and as we go on you will see a lot more of what they can do. Anyway, back to lists...

The append() method allows us to add items to the end of a list easily. The syntax for using this is list_name.append(thing we want to append). The next example shows how we would add an item to a list in this manner

mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
new_item = "Badger"
mammals.append(new_item)
print(mammals)
["Red Squirrel", "Hare", "Barn Owl", "Pine Marten", "Badger"]
Enter fullscreen mode Exit fullscreen mode

As well as appending a variable to a list such as mammals.append(new_item) we can also append the value directly mammals.append("Badger").

We can remove items from a list or delete an entire list using the delete.() method. Again the index value works in the same manner as slicing and we can give a range of index numbers or count backwards.

mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
del mammals[2]
print(mammals)
["Red Squirrel", "Hare", "Pine Marten"]
Enter fullscreen mode Exit fullscreen mode

Tuples


Tuples are very similar to lists, except once it is created we cannot alter the items it contains. tuples are created much like lists but using round brackets rather than square brackets. Tuples, like lists can contain any data type including other lists and tuples.

my_tuple = (12, 4.2, "Giraffe", False)
Enter fullscreen mode Exit fullscreen mode

We can access tuple items using index numbers in the same way as lists.

my_tuple = (12, 4.2, "Giraffe", False)
my_tuple[0]
12
Enter fullscreen mode Exit fullscreen mode

However, unlike lists we cannot modify the contents of a tuple using methods.


Dictionaries


"Baldrick, believe me, eternity in the company of Beelzebub and all his hellish instruments of death will be a picnic compared to five minutes with me and this pencil if we can't replace this dictionary." - Blackadder


In Python, dictionaries are collections of data organised into key : value pairs. This allows us to retrieve values by referencing the key to which that value is assigned. Dictionaries are created using curly brackets '{}'.

my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
Enter fullscreen mode Exit fullscreen mode

Accessing values in dictionaries is accomplished by using the key rather than an index number. In the above example if we wanted to access the value associated with the '2' key we would use:

print(my_dictionary[2])
Fox
Enter fullscreen mode Exit fullscreen mode

Keys do not have to be numbered or have any relation to one another at all

my_dictionary = {'name': "Simon", 17: 4.67, 'pig': True}
print(my_dictionary['name')
Simon
print(my_dictionary[17)
4.67
print(my_dictionary['pig')
True
Enter fullscreen mode Exit fullscreen mode

Dictionary values can be modified in much the same fashion as lists using the key for reference

Example 1

my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
my_dictionary[2] = "Cow"
print(my_dictionary)
{1: "Rabbit", 2: "Cow", 3: "Sheep"}
Enter fullscreen mode Exit fullscreen mode

Example 2

my_dictionary = {'name': "Simon", 17: 4.67, 'pig': True}
my_dictionary['name'] = "Percy"
print(my_dictionary)
{'name': "Percy", 17: 4.67, 'pig': True}
Enter fullscreen mode Exit fullscreen mode

To add key : value pairs to a dictionary we use the same method as changing an item. If the key does not already exist then it will be created.

my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
my_dictionary[4] = "Badger"
print(my_dictionary)
{1: "Rabbit", 2: "Fox", 3: "Sheep", 4: "Badger"}
Enter fullscreen mode Exit fullscreen mode

We also remove items using the del() method in the same way as with a list.

my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
del my_dictionary[1]
print(my_dictionary)
{2: "Fox", 3: "Sheep", 4: "Badger"}
Enter fullscreen mode Exit fullscreen mode

Finally, just like lists and tuples, dictionaries can have nested items including other dictionaries

my_dictionary = {1: 'One', 2: 'Two', 3: {'a': 'A', 'b': 'B'}, 4: 'four'}
Enter fullscreen mode Exit fullscreen mode

Accessing nested dictionary items is done in the same way as nested lists except we use the keys instead of index numbers for the parent dictionary and the nested item. In the following example we want the nested dictionary from key '3' and the item value from key 'b' in the nested dictionary.

my_dictionary = {1: 'One', 2: 'Two', 3: {'a': 'A', 'b': 'B'}, 4: 'four'}
nested_item = my_dictionary[3]['b']
print(nested_item)
'B'
Enter fullscreen mode Exit fullscreen mode

Take some time to make sure this all makes sense and practice creating and manipulating your own lists, tuples and dictionaries.
Python data structures and their associated methods are a topic well worth taking the time to learn. I have only briefly touched on what is possible here. To learn more follow this link and see if you can solve the following problem:

Task 1

  1. Create a list and name it my_list
  2. Give your list several items of different data types e.g. strings, integers, floats etc.
  3. Append your name as a string to the end of the list
  4. Delete the 3rd item in your list
  5. Substitute the 1st and 2nd items in your list with different items
  6. Delete the entire list

Task 2

  1. Create a tuple and name it my_tuple
  2. Try to append, delete or change values in my_tuple and note any errors or messages Python gives you

Task 3

  1. Create a dictionary and name it my_dict. In it, create the keys "genus", "species", "habitat" and "diet" and give them some appropriate values
  2. Add a new key "Lifespan" and give it an appropriate value
  3. Delete the "genus key and value

Conclusion


Hopefully, you are starting to see potential uses for data structures in your own projects. If not, don't worry you will get plenty of practice using them in the future. In the next article I am going to discuss flow control which enables our code to make decisions based on logical states. We will also be moving away from IDLE and using a new - tool the developers IDE! Exciting times ahead. I look forward to seeing you in part four. As always, constructive feedback is always appreciated. Thanks.

Simon.

Top comments (0)