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

(singke) #1

Click here to view code image


>>> list4 = ['Rich', 'Barbara', 'Katie Jane', 'Jessica']
>>> print(list4)
['Rich', 'Barbara', 'Katie Jane', 'Jessica']
>>>

Extracting Data from a List


The examples in the previous section show how to extract all the data values from a list at the same
time, by just referencing the list variable. You can retrieve individual data elements from list values
by using index values, just as with tuple values. Here’s an example:


>>> print(list2[0])
1
>>> print(list2[3])
4
>>>

You can also use a negative number for the list index. A negative index retrieves values starting from
the end of the list:


>>> print(list2[-1])
4
>>>

Notice that when you use negative index values, the -1 value starts at the end of the list, since -0 is
the same as 0.


Lists also support the slicing method of retrieving a subset of the data elements contained in the list
value, as in the following example:


>>> list4 = list2[0:3]
>>> print(list4)
[1, 2, 3]
>>>

Working with Lists


As mentioned earlier, the main difference between lists and tuples is that you can change the data
elements contained in a list value. This means there are lots of things you can do with lists that you
can’t do with tuples! This section walks through the different operations you can perform with list
values.


Replacing List Values


The most basic operation you can perform with a list value is to replace an individual data value
contained in the list. Doing this is as easy as using an assignment statement in your scripts, referencing
the individual list data value by its index, and assigning it a new value. For example, this example
replaces the second data value (referenced by index value 1 ) with the value 10 :


>>> list1 = [1, 2, 3, 4]
>>> list1[1] = 10
>>> print(list1)
[1, 10, 3, 4]
>>>

When you print the list value, it now contains the value 10 as the second data value.

Free download pdf