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

(singke) #1

In a much trickier operation, it’s possible to replace a subset of data values with another list or tuple
value. You reference the subset by using the list slicing method, as shown here:


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

Python replaces the data elements from index 1 up to index 3 with the data elements stored in the
tuple1 value.


Deleting List Values


You can remove data elements from within a list value by using the del statement, as shown here:


>>> print(list1)
[1, 10, 11, 4]
>>> del list1[1]
>>> print(list1)
[1, 11, 4]
>>>

You can also use slicing to remove a subset of data elements from the list, as in this example:


Click here to view code image


>>> list5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del list5[3:6]
>>> print(list5)
[1, 2, 3, 7, 8, 9, 10]
>>>

The slicing method allows you to customize exactly which data elements to remove from the list.


Popping List Values


Python provides a special function that can both retrieve a specific data element and remove it from
the list value. The pop() function allows you to extract a value from anywhere in a list. For
example, this example pops the fifth index value from the list6 list:


Click here to view code image


>>> list6 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list6.pop(5)
6
>>> print(list6)
[1, 2, 3, 4, 5, 7, 8, 9, 10]
>>>

When you pop a value from a list, the index values shift over to replace the popped index value.


If you don’t specify an index value in the pop() function, it returns the last data value in the list, like
this:


>>> list6.pop()
10
>>> print(list6)
[1, 2, 3, 4, 5, 7, 8, 9]
>>>
Free download pdf