leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python lists in action: Help Johnson find his way home

Estimated reading: 3 minutes 27 views
Python lists in action

We’ve covered ways to create lists, as well as many different ways to use them. In this tutorial, we’re going to write a small program that demonstrates some of the useful things that can be done with the list data type.

Help Johnson find his way home.

The story goes like this: Johnson’s first day at school, he has to go home by himself after school. Worried about finding his way home, he recorded the signs he passed from his home to school in a list. When he’s going home after school, get the next sign each time through the pop() method, so he knows what to do next.

Let’s start by creating an empty list roadSign. Start with an empty list, because Johnson doesn’t know which signposts he’ll encounter until he actually starts to leave for school. After that, you can append() the descriptions of important road signs on the way to school to the end of the roadSign list.

When Johnson gets home, just pop() each sign from the roadSign list.

>>> roadSign=[]
>>> roadSign.append("Johnson's house")
>>> roadSign.append("Fox streetlamp")
>>> roadSign.append("Guang Hualu kindergarten")
>>> roadSign.append ("Dog rescue center")
>>> roadSign.append("Samll street park")
>>> roadSign.append("Ri Tan School")

Here, an empty list called roadSign is created, and then the append() method is used to save all the important road signs passing by on the way to school in the roadSign list.

When Johnson arrives at the school, the roadSign list can be viewed. The first element is “Johnson’s house”, followed by “Fox streetlamp”, and so on, until the last element of the list, “Ri Tan School”.

>>> print(roadSign)
["Johnson's house", 'Fox streetlamp', 'Guang Hualu kindergarten', 'Dog rescue center', 'Samll street park', 'Ri Tan School']

When you want to go home, you only need to use the pop() method to take out the list elements one by one from the back to the front, and you will know how to go home.

>>> nextRoadSign=roadSign.pop()
>>> print(nextRoadSign)
Ri Tan School
>>> nextRoadSign=roadSign.pop()
>>> print(nextRoadSign)
Samll street park
>>> nextRoadSign=roadSign.pop()
>>> print(nextRoadSign)
Dog rescue center
>>> nextRoadSign=roadSign.pop()
>>> print(nextRoadSign)
Guang Hualu kindergarten
>>> nextRoadSign=roadSign.pop()
>>> print(nextRoadSign)
Fox streetlamp
> >> nextRoadSign=roadSign.pop()
>>> print(nextRoadSign)
Johnson's house

When Johnson gets home, we can see that roadSign is an empty list again.

>>> print(roadSign)

Leave a Comment