© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
A. ElumalaiIntroduction to Python for Kids https://doi.org/10.1007/978-1-4842-6812-4_11

11. Lots and Lots of Information!

Aarthi Elumalai1  
(1)
Chennai, Tamil Nadu, India
 

In the previous chapter, we learned all about automating your code with for and while loops. We also looked at the break and continue statements and created a lot of colorful, mini projects.

In this theory-intensive chapter, let’s look at the various built-in data structures offered by Python. Let’s look at how to use these data structures to store more than one value at a time in a single variable, and let’s look at practical examples of using these data structures in real-world programs.

Store more than one value

So far, we’ve just been storing one value at a time. Of course, we can change the values, but we can’t store two values in the same place. Isn’t that a little inconvenient? Let’s say I want to store six different color values so I can use them in my code, one after the other.

How would I do that? I’d probably do something like this:
color1 = 'Red'
color2 = 'Orange'
color3 = 'Blue'
color4 = 'Yellow'
color5 = 'Green'
color6 = 'Violet'

Then I’d have to remember and refer each of those values every time I want them used in my code. Whoa…that’s a long-drawn-out process.

What if I can store all six colors in the same place, in the same variable? It’ll look something like Figure 11-1.
../images/505805_1_En_11_Chapter/505805_1_En_11_Fig1_HTML.jpg
Figure 11-1

Multiple values in the same variable

This is called a data structure in Python. Look at how the data is structured (organized) and stored? Hence the name. There are four such pre-made data structures that can be used to store multiple values in the same location. You save a lot of lines of code, time, and your code is a lot more efficient too. You can store different types of data as well. The same data structure could have strings, numbers, and Booleans stored in them.

Accessing this data is easy too. You’d just have to follow a similar format to the one we use while accessing individual characters in a string. I’ll get to that in a bit.

Let me show you the four data structures first:

../images/505805_1_En_11_Chapter/505805_1_En_11_Figa_HTML.jpg
  • List: Python is indeed an easy-to-learn language, isn’t it? The keywords used in this language are very easy to remember. A list is just that. It’s a list of information, but it is ordered. The individual values in a list can be changed, and lists allow duplicate values inside of them.

  • Tuple: A tuple is similar to a list. The only difference is that the values cannot be changed once fixed. That means you can’t add or delete values either.

  • Set: A set, unlike a list of a tuple, is unordered, and there are no indices to access specific values from. It doesn’t allow for duplicate values as well, since the values are unordered.

  • Dictionary: As the name implies, a dictionary has the values stored in a word : description format. Dictionaries are unordered as well, but they can be changed and the “word”, which is called a “key” in Python, acts as an index through which you can access the values (descriptions).

You’re probably squinting at the pages of this book right now. Don’t worry at all. At a glance, these data structures look intimidating. They’re definitely not. I’ll explain them with fun and easy-to-understand examples from the next section, and you’ll understand everything in no time. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figc_HTML.gif

Lists

Let’s look at lists first. It’s quite easy to create them. Separate the multiple values you want stored in your list by commas and enclose everything inside of square brackets ([]) and you have yourself a list. Would you like to try?

Let’s convert the six lines of code we wrote in the previous example into a list, shall we?
colors = ['Red', 'Orange', 'Blue', 'Yellow', 'Green', 'Violet']

The preceding example just has strings in them (hence the quotes), but you can create a list of just numbers, or just Booleans, or a combination of two or more of them. Just create what you want based on your need.

You’re probably squinting at the pages of this book right now. Don’t worry at all. At a glance, these data structures look intimidating. They’re definitely not. I’ll explain them with fun and easy:
a = [1, 'Hello', True, False, 34.5, '*']

The preceding code is a list of heterogenous values (different data types).

Accessing values in a list

Okay, so we have a list of values. How do we access them? Would you like to take a guess? You know how already.

Yep, with indices, just like we did for our strings. The first value in the list has an index of 0, the second an index of 1, and so on.

Let’s say I want the third value accessed and printed in list “a”. It’s at the index 2.
print(a[2])
Run the preceding code, and you’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/dataStructures.py
True

Successfully accessed!

You can do negative indexing just like you did with your strings. So, to access the last element (value) in the list, I’d just have to give –1.
print(a[-1])
Run the preceding code, and you’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/dataStructures.py
*

It works! Yippee! ../images/505805_1_En_11_Chapter/505805_1_En_11_Figd_HTML.gif

Slice a list!

If negative indexing and accessing work, just like with your strings, then extracting a part of a list using ranges should work as well, right? Let’s test.

Let’s say I want to extract the second through fifth values, with indices 1 through 4. My range should be 1:5 since the last number in the range is not included.
print(a[1:5])
['Hello', True, False, 34.5]
Oh yes, it works! Then extracting through negative indices should work as well, right? Let’s say I want everything from the negative third index extracted.
print(a[-6:-3])
You already know how negative indices work right? If I run the preceding code, I’ll get this:
[1, 'Hello', True]
You can change values as well. Let’s say I want the second value (string) to be changed to a number. Then, I’d have to access the second value (first index) and assign something else to it.
a[1] = 100
print(a)
Let’s print the entire list to see how it’s changed now:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/dataStructures.py
[1, 100, True, False, 34.5, '*']

List manipulation on fire!

You have a lot of pre-defined methods that can be used to manipulate your list in multiple ways. Remember the methods we saw with your strings? You’ll find some of them repeated here as well. Are you ready to play with your list? Yes!

As usual, you can find the length of your string with the len() method:
a = [1, 'Hello', True, False, 34.5, '*']
print(len(a))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
6

Yes! Our list’s length is 6. It works.

You have a complete list of methods for each of the data structures we’ll be looking at in this chapter. So, I’m just going to link you to the page in the Python docs where all those methods and their explanations are listed.

Here it is: https://docs.python.org/3/tutorial/datastructures.html.

That said, let’s just look at some of the most important methods in this chapter, alright?

Copy and append

The append() method appends or adds an element at the end of the list :
 a.append('new')
print(a)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[1, 'Hello', True, False, 34.5, '*', 'new']
The copy method creates a copy of the list, and this copy can be assigned to any variable to create a copied list:
b = a.copy()
print("List b contains: {}".format(b))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
List b contains: [1, 'Hello', True, False, 34.5, '*', 'new']

Count and clear

Lists can have duplicate values, am I right? Let’s say we have a list of numbers where the numbers are duplicated, and I want to check how many times a particular number appears in the list. I can use the “count” method to achieve that.
l = [1,2,1,1,4,5,3,5,3,2]
print(l.count(1))
I’ve started the syntax with the name of the list, “l”, then the name of the method, “count”, and then I’ve mentioned the value I wanted to count (1). If it were a string, I’d have mentioned the same within quotes. Let’s run the preceding code, and we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
3

We got the right answer! The number 1 appeared thrice in the list.

You can clear the entire list using the “clear” method.
l.clear()
print(l)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[]

We have ourselves an empty list now!

Concatenation

You can use the “extend” method to concatenate or join two lists.
list1 = [1,2,3,4,5]
list2 = [6,7,8,9]
list1.extend(list2)
print(list1)

As you can see in the preceding code, the elements of the list you want listed first come first, then a period (“.”), and then the “extend” method, and then inside the brackets, you can mention the name of the list you want joined to the first list.

Let’s run the preceding code, and we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Look at that! Perfectly joined, and in the order we wanted as well. ../images/505805_1_En_11_Chapter/505805_1_En_11_Fige_HTML.gif

Search inside your list

The “index” method returns the index of the very first instance of the value you are searching for. For example, if you want to find the number 3 in a list, but its duplicated twice, then only the index of the first occurrence of 3 would be returned. Let me show an example:
list1 = [1,2,3,2,3,1,3]
print(list1.index(3))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
2

Look at that! 3 exists thrice in the list, but we only got the index of the first 3. Sweet!

But you can narrow that search down, if you’d like. What if I want to find 3 in the last half of the list, maybe starting from the third index? You can specify the start and end of your search as arguments as well. Let me show you how:
print(list1.index(3,3,6))

I’m asking my program to search for 3 from indices 3 to 5. You know how these things work right? The last value in the range won’t be included. So, if the last value is 5, then your program will only search until the fifth index.

When I run the preceding code, I’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
4

Look at that! We got the index of the second instance of 3 in the list. Nice!

Add and remove elements

You know how to add elements to a list using your square brackets, and you can change elements using the same method as well. But what if I want to insert elements in the middle of the list so that the other values still exist, but just move one step further?

You can use the insert method to achieve that. The first argument in the method is the position in which you want the value, and the second argument is the value you want added.
colors = ['Red', 'Orange', 'Blue']
colors.insert(1,'Green')
print(colors)
I’ve added the value ‘Green’ to the first index. Now ‘Orange’ should be pushed one step further. Let’s check, shall we?
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
['Red', 'Green', 'Orange', 'Blue']

Yep, it worked! ../images/505805_1_En_11_Chapter/505805_1_En_11_Figf_HTML.gif

The pop() method removes the last element in the list by default. If you give a position (index) though, it’ll remove the element at that position.

Let’s try removing the second element in the preceding list, which is the element we just inserted, okay?
colors.pop(1)
print(colors)
When we run the entire code, we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
['Red', 'Green', 'Orange', 'Blue']
['Red', 'Orange', 'Blue']

Look at that! The list originally had four elements, and we successfully removed the second element using the pop() method.

Alternatively, you can use the remove() method as well. The only difference is you can specify the exact element you want removed.

Our list currently has ['Red', 'Orange', 'Blue']. I don’t want blue anymore. Why don’t we try removing it?
colors.remove('Blue')
print(colors)
Let’s see if it worked:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
['Red', 'Orange']

Yay! It worked!

It’s getting a bit too long, isn’t it? Don’t worry! We’re almost done. Then let’s distract us with a fun little project, deal? ../images/505805_1_En_11_Chapter/505805_1_En_11_Figg_HTML.gif

Reverse and sort

There’s another method called the reverse() method. Can you guess what it does? Exactly! It reverses the elements in a list. Let’s try!
li = [1,2,3,4,5]
li.reverse()
print(li)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[5, 4, 3, 2, 1]

Success!

Finally (yes, finally), there’s another method called the sort() method that sorts the elements by alphabetical order.

By default, the sorting happens in the ascending order.
colors = ['Red', 'Orange', 'Blue', 'Yellow', 'Green', 'Violet']
colors.sort()
print(colors)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
['Blue', 'Green', 'Orange', 'Red', 'Violet', 'Yellow']

It’s like magic! :O

Does this work with numbers?
li = [1,4,3,6,2,8,7,9,5]
li.sort()
print(li)
When you run the above code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Hehe, it works.

But what if I want the sorting done in the descending order? In that case, I’ll modify the sort() function call like this:
li.sort(reverse=True)
print(li)

When you give the argument as reverse=True, your program will sort your list in the descending order. The default is reverse=False, which sorts the list in the ascending order. When something happens by default, you don’t need to mention it as an argument.

Let’s run the preceding code, and we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[9, 8, 7, 6, 5, 4, 3, 2, 1]

Nice…my list is in the descending order now. Python lets us do pretty much anything, doesn’t it?

More fun with lists!

You can check if something exists in a list using the “in” keyword:
print('Hello' in a)
In the preceding line of code, we’ve asked if the string ‘Hello’ is a part of the list.
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
False
The result is false. We changed the second value from ‘Hello’ to 100, remember? So, ‘Hello’ is no longer a part of the list. As with everything in Python, these searches are case sensitive as well. So, ‘Hello’ is different from ‘hello’, and if the string was ‘Hello there!’, then you need to search for the entire thing. Partial searches don’t work. Let me show you:
a[1] = 'Hello there!'
print('Hello' in a)
I’ve changed the second value to ‘Hello there!’, and when I search for ‘Hello’ in the list “a”, let me see what I get:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
False

Look at that. It’s still a false because you haven’t searched with the correct term.

Now that you know how lists work, I want to get back to a previous topic. Remember “for” loops? And do remember my promise to revisit for loops when I teach you about lists? We’re here now!

You can iterate through a list using your for loop. It’s quite simple. Just create your list, and then replace that in place of a range, like this:
l = [1,2,3,4,5]
for i in l:
    print(i)
The result is this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
1
2
3
4
5
Alternatively, you can also directly specify the list, like this:
for i in [1,2,3,4,5]:

Modify and run your code with the preceding line of code and you’ll notice that you get the same result.

Apart from the “extend” method, you can also use the “+” operator to concatenate two lists, just like you do with strings, like this:
list1 = [1,2,3,4,5]
list2 = [6,7,8,9]
list1 += list2
print(list1)
Alternatively, you can create a new variable and assign the value of list1 + list2 to it. Either works.
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

The “clear” method just clears the list. But if you use the “del” keyword, you can delete the list in its entirety. Would you like to check?

Let’s delete the preceding list, shall we?
del list1
print(list1)
When I try to print list1 after I deleted it, I’ll get an error, like the following:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
Traceback (most recent call last):
  File "C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py", line 10, in <module>
    print(list1)
NameError: name 'list1' is not defined

Look at that! ‘list1’ was completely erased from our program.

You can do the same for elements in a list as well.
a = [1, 'Hello', True, False, 34.5, '*']
del a[2]
print(a)
I’ve asked my program to delete the third element in the list. Let’s print, and we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
[1, 'Hello', False, 34.5, '*']

The third value “True” no longer exists in list “a”.

Mini project – multi-colored automated star

In this project, I’m going to draw a star with Python, but each side is going to have a different color. That’s where my list comes in. I’m going to create a list of five colors and run a for loop through it. For every iteration of the for loop, Turtle will draw a side of the star with a new color from the list.

Let’s see how it’s done, shall we?
  1. 1.

    I’m going to start with the usual lines of code to set up Turtle:

     
import turtle
s = turtle.getscreen()
t = turtle.Turtle()
  1. 2.

    I’m going to set the pen size as 5 so my image looks good.

     
t.pensize(5)
  1. 3.

    Next, I’m going to create a variable called “colors” and assign a list of five colors, ‘Red, ‘Brown’, ‘Green’, ‘Blue’, and ‘Orange’ to it. I’ve already given you a link to a list of colors, so choose your preferred set of colors. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figh_HTML.gif

     
colors = ['Red', 'Brown', 'Green', 'Blue', 'Orange']
  1. 4.

    Next, I’m going to create a temporary variable x that iterates, via the for loop, through the entire list:

     
for x in colors:
  1. 5.

    For every iteration of the loop, my pen color will change to the current color in the temporary variable “x”. I’ll ask my Turtle to move forward by 200 points and turn right by 144 points because a star’s outer angle is 144 degrees and I need to turn that much to get a proper star as my result.

     
t.pencolor(x)
t.forward(200)
t.right(144)
  1. 6.

    That ends my for loop and the indentation. Finally, I’m going to hide my turtle.

     
t.hideturtle()
turtle.hideturtle()
When you run the preceding code, you’ll get this (Figure 11-2).
../images/505805_1_En_11_Chapter/505805_1_En_11_Fig2_HTML.jpg
Figure 11-2

Multi-colored star

Yes! We got it! Why don’t you try the same with different colors or different shapes? Or maybe, you could try to randomly choose colors for every iteration? You know how to do that already (I’ve taught you how), so go ahead and try. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figi_HTML.gif

Tuples

Now that we’ve taken a detailed look at lists, you’ll find the remaining three data structures easy to understand, so I’ll quickly go through them, alright?

As I’ve mentioned before, a tuple is similar to a list. The only difference is that it’s ordered (just like a list, with index and all), but unchangeable (unlike a list). What does that mean for us? Well, it just means that you can’t add, delete, or change the elements in the list.

Now that’s a bummer! Does that mean a tuple is not as cool as a list? Well, I wouldn’t say that, exactly. You know, you might need to create a list that you don’t want anyone to manipulate later, am I right? Something like a “read-only” list? In those instances, a tuple is your best friend. Otherwise, go for a list, 100%. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figr_HTML.gif

You can create a tuple with parenthesis, with the tuple items separated by commas, like this:
t1 = ('Red', True, 2, 5.0)
print(t1)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
('Red', True, 2, 5.0)

Most of the things in a tuple follow the same format as that of a list, so I’m just going to list them, and I want you to try them out in your computer. It’ll be our little activity, okay?

Just like you do with your lists, you can access the elements in a tuple with square brackets.

t1[1] will return the second element, True. Tuples are indexed just like lists, where the first index is 0.

Just like lists, you can use negative indexing to access values in a tuple. So, t1[–1] will return the last element in the list.

You can slice a tuple using indices as well.

If you wanted to extract the second through the fourth value (last), then you can specify t1[1:4]) or just t1[1:], since we want everything from the first index anyway.

If you wanted to write the same with negative indices, you’ll do it like this: t1[–3:] because you want everything from –3 to the end of the tuple.

You can use the len(t1) method to get the length of the tuple and use the “in” keyword to check if something is inside a tuple, just like you do with your lists. Why don’t you try them out and see?

And then there’s your “for” loop. You can loop through tuples as well. The process is the same.
for x in t1:
    print(x)

Why don’t you run the preceding code and check if looping works with tuples?

Ah well, so far, tuples look like lists written within parenthesis. What’s their use, anyway? Remember how I told that tuples are unchangeable? And we haven’t tried changing elements or adding elements to our tuple yet, have we? Let’s try.

I’m going to try changing the value of the second element to False to True.
t1[1] = False
Let’s run our code, and we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
Traceback (most recent call last):
  File "C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py", line 4, in <module>
    t1[1] = False
TypeError: 'tuple' object does not support item assignment

Oops, we got an error! Tuples don’t support item assignment, meaning their elements cannot be changed.

Try adding a new element to the tuple. Access the fourth index (fifth element) and add something. When you do that, you’ll notice that you encounter the same error.

This is most important use of a tuple. You can create unchangeable lists that can be used to store sensitive information that shouldn’t be changed. What if you create a program to store the id numbers of your classmates? You wouldn’t want those changed, would you? Then store them in a tuple. Simple as that!

But, just like in your lists, you can delete the entire tuple using the “del” keyword, like this:
del t1

If you try to access t1 now, you’ll get an error.

Tuples have methods as well, but they only have few methods that can be used to access elements and none that can manipulate the elements or the tuple itself.

The “count” method returns the number of times a value repeated in a tuple. Remember, tuples can have duplicate values, just like lists.

The “index” method returns the position (index) of the value in a tuple.
t1 = ('Red', True, 2, 5.0)
print(t1.index(5.0))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
3

Yes! 5.0 is in the third index (fourth position).

That’s it for tuple. It was quite simple, wasn’t it? Let’s look at the next data structure in the list next.

Sets

Do you remember what I told you about sets? They are unordered and they cannot have duplicate values. It’s a double whammy. But sets have their uses too. Would you like to take a look at it?

Great! Well, you write sets within flower brackets, like this:
colors = {'Red', 'Orange', 'Blue'}

The preceding code is a set of the colors ‘Red’, ‘Orange’, and ‘Blue’.

But! Sets are unordered. So, would those values really appear as we created them? Would you like to check?
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'Blue', 'Orange', 'Red'}

Whoa, look at that! The order is changed. Can you run the program again and tell me what you get?

The order changed again, didn’t it? How cool is that? ../images/505805_1_En_11_Chapter/505805_1_En_11_Figj_HTML.gif

But we do have a problem now. Sets are unordered. So how do we access the elements if we don’t know the indices? How do we add elements to the set? How do we insert elements in a particular position? Well, unfortunately, there are certain things you can’t do with a set, and anything that pertains to order comes under that.

So, you can’t use the square brackets to find an element in a particular position. But, you can use the “in” keyword to check if an element exists in a set:
print('Red' in colors)

Run the preceding code, and you’ll get True.

You can also loop through a set, just like you do with your list and tuple.
for i in colors:
    print(i)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
Orange
Blue
Red
But how would you add elements to the set when you don’t know the index? There is the add() method that can be used to add individual elements, though you won’t know where they’ll end up.
colors.add('Green')
print(colors)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'Blue', 'Green', 'Orange', 'Red'}

How interesting it that? We added ‘Green’ to the set, and it ended up in the second position. Run the program again, and you’ll find it somewhere else.

What if I want to add more than one color to my set? I can save space by using the “update()” method.

Create a list of values within square brackets and place that within the parenthesis. Let me try to add both ‘Green’ and ‘Yellow’ to my set:
colors.update(['Green','Yellow'])
print(colors)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'Red', 'Yellow', 'Blue', 'Orange', 'Green'}

Look at where Green and Yellow ended up. :D

Just like with your lists, you can use the len() method to find the length of a list as well.

Now, let’s look at the rest of the methods for manipulating a set, shall we? I’ll just list the ones that are similar to the ones we saw with our lists.

In a list, the pop() method removes a random value and not the last one. You can use the remove() method to remove a particular value by mentioning it as an argument.

Alternatively, you can use the “discard()” method to remove a particular element as well. The only difference between discard and remove is that discard doesn’t raise an error if the mentioned element doesn’t exist. This is important in real-world programming. When running a program, you don’t want errors that stop the program execution because one line of code was wonky.

The clear() method clears the set, and the copy() method copies the list.

You can use the “del” keyword to delete the entire set, but you can’t use it to delete a particular element since you they don’t have fixed indices that you can access.

Finally, let’s look at joining sets. You can join two sets using the “union()” or “update()” methods.
colors = {'Red', 'Orange', 'Blue'}
colors1 = {'Green', 'Yellow'}

Let’s say we have two sets, colors and colors1 with their own values, and we want them merged into the colors set.

You can use the union() method. It creates a new set with the values in both the sets.
colors2 = colors.union(colors1)
print(colors2)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'Yellow', 'Green', 'Red', 'Blue', 'Orange'}
But update just updates the first set in the syntax with values from both the sets. If you print out the second set in the syntax, you’ll notice that it’s unchanged. Update just changes the first set.
colors.update(colors1)
print(colors)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'Orange', 'Yellow', 'Red', 'Blue', 'Green'}

We’re done with sets as well. Yay! You’re becoming quite the pro Python programmer now. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figk_HTML.gif

Dictionaries

The last data structure in this list is the dictionaries . Let’s quickly finish it and go back to some more fun mini projects, so are you with me? Yes!

So, dictionaries are unordered, but they are indexed and can be changed. The thing I love about dictionaries is that they can be used to model real-world stuff. Do you want to see?
../images/505805_1_En_11_Chapter/505805_1_En_11_Figb_HTML.jpg

Dictionaries are created within flower brackets as well, but inside, you need to mention the values in key:value pairs. The “key” is the index here.

Since I want my dictionaries to model real-world objects, I’m going to create a dictionary that represents a person’s characteristics: their name, age, eye color, hair color, and so on.

This is how I’d do that:
person1 = {"name":"Susan","age":9,"pet":"Barky","hair":"black","eyes":"blue"}

I’ve created a dictionary, “person1”. Her name is Susan, she’s 9 years old, her pet’s name is Barky, and she has black hair and blue eyes. Looks great, doesn’t it?

Now, let’s manipulate this dictionary. You can access values with the “keys” like this:
print(person1["name"])
Or
print(person1.get("name"))

Remember that you have to mention the keys within quotes everywhere.

Run either of these lines of code, and you’ll get the same result:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
Susan

Her name!

You can also change values. Susan is actually 8, not 9! Quick, let’s correct her age before she gets sad!
person1["age"] = 8
print(person1)
Run this, and you’ll get the following:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'name': 'Susan', 'age': 8, 'pet': 'Barky', 'hair': 'black', 'eyes': 'blue'}

Nice!

You can also add a new key:value pair the same way. Let’s add a key, gender, and make it female.
person1["gender"] = 'female'
print(person1)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'name': 'Susan', 'age': 9, 'pet': 'Barky', 'hair': 'black', 'eyes': 'blue', 'gender': 'female'}

It was added, yay!

You can check if a key exists using the “in” keyword.
print('pet' in person1)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
True

Yes, “pet” is one of the keys of the dictionary.

Just like usual, you can find the length of the dictionary using the “len” method.

The following will delete the dictionary:
del person1

person1.clear() will empty the dictionary.

You can use the copy() method to copy the dictionary.

As usual, you can loop through a dictionary, but since our dictionary has a key and a value each, we can do the looping in different ways.

Let’s create a smaller dictionary first:
person1 = {"name":"Susan","age":8}
Let’s loop through all the keys first and print them:
for i in person1:
    print(i)
This should print all the keys:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
name
age

Yes!

If you want the values, just change the position of “i”, like this:
for i in person1:
    print(person1[i])
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
Susan
8

We got just the values now. Whoo!

Alternatively, you can loop through both keys and values, like this, using the items() method:
for i,j in person1.items():
    print("{} = {}".format(i,j))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
name = Susan
age = 8

Nice! ../images/505805_1_En_11_Chapter/505805_1_En_11_Figl_HTML.gif

Let’s just look at one last thing before we end this. pop() removes the given key:value pair, while popitem() removes the last item in the dictionary.
person1.pop("name")
print(person1)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'age': 8}

Age is the only key left! ☹

Let’s rewrite the dictionary again, and this time, try popitem().
person1.popitem()
print(person1)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
{'name': 'Susan'}

Now, ‘name’ is the only key left!

That’s it for dictionary! ../images/505805_1_En_11_Chapter/505805_1_En_11_Figm_HTML.gif

Mini project – never-ending colors

Another simple project with a twist! ../images/505805_1_En_11_Chapter/505805_1_En_11_Fign_HTML.gif We are going to randomly change the background colors after an interval of 1 second while printing the current color on the turtle screen.

The twist? We’re going to use a new package called “time” to make the turtle screen pause between each color change. Ready? Let’s get going!
  1. 1.
    So, as I said, we need both the “time” and the “turtle” modules. Let’s import both.
    import time
    import turtle
     
  2. 2.
    Next, let’s set up turtle as usual.
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  3. 3.
    Once set up, let’s move the pen we just created to the position from where we want it to write the colors. That’s going to be the point –80,0.
    t.penup()
    t.goto(-80,0)
    t.pendown()
     
  4. 4.
    Now, let’s create a dictionary of colors. I’m creating a dictionary and not a list this time, because I’m going to make the keys capitalized versions of their values (colors) so I can write them on the screen.
    colors = {'RED':'Red', 'BROWN':'Brown', 'GREEN':'Green', 'BLUE':'Blue', 'ORANGE':'Orange'}
     
  5. 5.
    Before we start drawing, let’s hide the turtles. You’ll see why when you run the program. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figs_HTML.gif
    t.hideturtle()
    turtle.hideturtle()
     
  6. 6.

    Now, here comes the fun part. We want this program to be never ending, remember? So, it’s obvious that we need a loop, but what kind of loop? How do we create a never-ending loop? Remember how I said “while” loops can literally run forever if we’re not careful? That is, if the condition doesn’t become false at one point.

     
What if we do exactly that? What if we make the while loop’s condition “True” and just that? Then, if there’s no break statement anywhere within the while loop, it really will run forever.
#never ending loop
while True:
  1. 7.

    Simple! Next, let’s create for loop that’ll loop through the “colors” dictionary.

     
for x in colors:
  1. 8.
    For every iteration, let’s change the background color of the turtle screen to the next color in the for loop (the value). Also, let’s write the key value (x) in Arial, 50 pt, bold text.
    turtle.bgcolor(colors[x])
    t.write(x,font=('Arial',50,'bold'))
     
  2. 9.

    Now, after every color change, we need a 0.5-second delay, or gap, before the next color change (for loop iteration) happens. This is where the “time” package comes in. It has a built-in function called sleep() which will literally pause the loop for the number of seconds mentioned. In our case, it’s going to be 0.5.

     
time.sleep(0.5)
  1. 10.

    Okay, this should technically be it, but if we leave it at this, then you’ll notice that your turtle writes the next text on top of the old text, and things will continue to get messy. Why don’t you try and see?

     
Your turtle package comes with a clear() function that clears the screen. So, why don’t we clear the screen before we change the next color and draw the next text?
t.clear()
That’s it! Let’s run this now, and we’ll get this (Figure 11-3).
../images/505805_1_En_11_Chapter/505805_1_En_11_Fig3_HTML.jpg
Figure 11-3

Never-ending colors

You’ll notice that the program loops through the “colors” dictionary, infinitely. Sweet, huh? ../images/505805_1_En_11_Chapter/505805_1_En_11_Figo_HTML.gif

Mini project – first and last name reversal

In this project, this is what I want happened: When I enter a name, for example, Susan Smith, I want my program to return the reversal of it, that is, Smith, Susan.

It’s more of a puzzle than a mini project. The logic is very simple:
  1. 1.
    Let’s start the program by getting the name as the input. The condition is their first and last name needs to be separated by a single space. This is important. You’ll see why.
    name = input('Please Enter your first and last name, separated by a space: ')
     
  2. 2.

    As I said, the format of the string input is important to make this program work. So, I’m going to count the number of single spaces in the string. If it’s none, or more than one, then the program stops with an error message.

    Let’s create a variable count and assign it to 0 to start with.

     
count = 0
  1. 3.
    Next, let’s create a for loop that loops through the string we just got. Whenever there’s a single space, let’s add 1 to count.
    for i in name:
        if i == ' ':
            count += 1
     
  2. 4.
    If count is just 1, then we’re good to go. Let’s convert the string to a list by using the split method, where the first and last names are separated into separate list items with the single space as the delimiter used.
    if count == 1:
        #Convert string to list, where the condition is the space
        l = name.split(' ')
     
  3. 5.
    Next, let’s reverse the list.
    #Reverse list
    l.reverse()
     
  4. 6.
    Finally, let’s insert a comma with a space to the first position of the list, so when we join everything, we get the exact format we want.
    #Add a comma, with a space, in the first position of the list
    l.insert(1,', ')
     
  5. 7.
    Now let’s join the list into a string with an empty string as the join condition. This way, everything gets stuck together, and the only thing separating the last and first names is “, ”.
    #Join a list into a string
    name = ''.join(l)
     
  6. 8.

    Finally, print everything.

     
print('Your reversed name is: {}'.format(name))
  1. 9.
    If the count isn’t 1, print an error message.
    else:
        print('Please Enter your name in the correct format')
     
Now, let’s run the program!
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32dataStructures.py
Please Enter your first and last name, separated by a space: Susan Smith
Your reversed name is: Smith, Susan

Perfect! ../images/505805_1_En_11_Chapter/505805_1_En_11_Figp_HTML.gif

Summary

In this chapter, we took a deep dive into the four pre-defined data structures offered by Python, namely, list, set, tuple, and dictionary. We looked at how to create them, delete them, manipulate them, and so much more. Finally, we looked at how to use them in programs and why they’re useful in real-world programming scenarios.

In the next chapter, let’s take a small break from all the learning and start creating! We’ll be creating a lot of mini projects. ../images/505805_1_En_11_Chapter/505805_1_En_11_Figq_HTML.gif

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.82.167