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

(singke) #1
print("One value in the list is", x)

One value in the list is 1
One value in the list is 15
One value in the list is 46
One value in the list is 79
One value in the list is 123
One value in the list is 427
>>>

The x variable contains an individual data value from the list for each iteration of the for statement.
The print statement displays the current value of x in each iteration.


Sorting and Reversing Revisited


In the “Working with Lists” section earlier this hour, you saw how to sort and reverse the data values
inside a list. There are also functions that allow you to sort or reverse the data values but return the
result as a separate list, keeping the original list intact.


The sorted() function returns a sorted version of the list data values:


Click here to view code image


>>> list15 = ['oranges', 'apples', 'pears', 'bananas']
>>> result1 = sorted(list15)
>>> print(list15)
['oranges', 'apples', 'pears', 'bananas']
>>> print(result1)
['apples', 'bananas', 'oranges', 'pears']
>>>

The original list15 variable remains the same, and the result1 variable contains the sorted
version of the list.


The reversed() function returns a reversed version of list data values, but it is a little tricky.
Instead of returning a list, it returns an iterable object, which can be used in a for statement but
cannot be directly accessed. Here’s an example:


Click here to view code image


>>> list15 = ['oranges', 'apples', 'pears', 'bananas']
>>> result2 = reversed(list15)
>>> print(result2)
<list_reverseiterator object at 0x01559F70>
>>> for fruit in result2:
print("My favorite fruit is", fruit)

My favorite fruit is bananas
My favorite fruit is pears
My favorite fruit is apples
My favorite fruit is oranges
>>>

If you try to print the result2 variable, you get a message that it’s a reverseiterator object
and not printable. You can, however, use the result2 variable in the for statement to iterate
through the reversed values.


Creating Lists by Using List Comprehensions

Free download pdf