result2 = list1.pop()
print("The second item removed is", result2)
# add one more data value and see where it goes
list1.append(40.0)
print("The final version is", list1)
The script0801.py script creates an empty list by using the list1 variable, and then it appends
a few values into it. Then it retrieves a couple values by using the pop() function. When you run the
script0801.py program, you should get this output:
Click here to view code image
pi@raspberrypi ~/scripts $ python3 script0801.py
The starting list is [10.0, 20.0, 30.0]
The first item removed is 30.0
The second item removed is 20.0
The final version is [10.0, 40.0]
pi@raspberrypi ~/scripts $
Using stacks is a common way to store values while performing calculations in long equations, as you
can push values and operations into the stack and then pop them out in reverse order to process them.
Concatenating Lists
You have to be a little careful about using the append() function with lists. If you try to append a
list onto a list, you may not get what you were looking for, as shown here:
>>> list8 = [1, 2, 3]
>>> list9 = [4, 5, 6]
>>> list8.append(list9)
>>> print(list8)
[1, 2, 3, [4, 5, 6]]
>>>
When you use a list object with the append() function, Python appends the list as a single data
value! Thus, the list8[3] value is now itself a list value in this example:
>>> print(list8[3])
[4, 5, 6]
>>>
If you wanted to concatenate the list8 and list9 lists, you need to use the extend() function,
like this:
>>> list8 = [1, 2, 3]
>>> list9 = [4, 5, 6]
>>> list8.extend(list9)
>>> print(list8)
[1, 2, 3, 4, 5, 6]
>>>
Now the result is a list that contains the individual data values from the two lists. This also works
using the addition sign, as with tuples:
>>> list8 = [1, 2, 3]
>>> list9 = [4, 5, 6]
>>> result = list8 + list9
>>> print(result)