Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Adding New Data Values


You can add new data values to an existing list by using the append() function, as shown here:


>>> list7 = [1.1, 2.2, 3.3]
>>> list7.append(4.4)
>>> print(list7)
[1.1, 2.2, 3.3, 4.4]
>>>

The append() function adds the new data value to the end of the existing list.


You can insert a new data value into a list at a specific index location by using the insert()
function. The insert() function takes two parameters. The first parameter is the index value
before which to place the new data value, and the second parameter is the value to insert. Thus, to
insert a new data value at the front of the list, you use this:


>>> list7.insert(0, 0.0)
>>> print(list7)
[0.0, 1.1, 2.2, 3.3, 4.4]
>>>

To insert a data value in the middle of the list, you use this:


Click here to view code image


>>> list7.insert(3, 2.5)
>>> print(list7)
[0.0, 1.1, 2.2, 2.5, 3.3, 4.4]
>>>

The insert() statement inserts the value 2.5 before index 3 in the list, making it now the new
index 3 value and pushing the other index locations down one position in the list.


You can use a combination of the append() and pop() functions to create a storage area
commonly called a stack in your Python scripts. You push data values onto the stack and then retrieve
them in the opposite order from which you pushed them (called last-in, first-out [LIFO]). To do this,
you just use the append() function to add new data values to an empty list and then retrieve them by
using the pop() function, without specifying the index. Listing 8.1 shows an example of doing this in
a script.


LISTING 8.1 Using append() and pop() to work with a list


Click here to view code image


#!/usr/bin/python3

list1 = []
# push some data values into the list
list1.append(10.0)
list1.append(20.0)
list1.append(30.0)
print("The starting list is", list1)

# pop some values and see what happens
result1 = list1.pop()
print("The first item removed is", result1)
Free download pdf