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

(singke) #1

Creating Lists by Using List Comprehensions


As mentioned earlier this hour, in the “Creating a List” section, there’s a fourth way of creating lists:
using a list comprehension. Using a list comprehension is a shortcut way to create a list by
processing the data values contained in another list or tuple.


This is the basic format of a list comprehension statement:


Click here to view code image


[expression for variable in list]

The variable represents each data value contained in the list, as a normal for statement. A list
comprehension applies the expression on each variable to create the new data values in the new list.
Here’s an example of how it works:


Click here to view code image


>>> list17 = [1, 2, 3, 4]
>>> list18 = [x*2 for x in list17]
>>> print(list18)
[2, 4, 6, 8]
>>>

In this case, the list comprehension defines the expression as x*2, which multiplies each data value
in the original list by 2.


You can make the expression as complex as you like. Python just applies the expression—whatever it
is—to the new data values in the new list. You can also use list comprehensions with string functions
and values, as shown here:


Click here to view code image


>>> tuple19 = 'apples', 'bananas', 'oranges', 'pears'
>>> list19 = [fruit.upper() for fruit in tuple19]
>>> print(list19)
['APPLES', 'BANANAS', 'ORANGES', 'PEARS']
>>>

In this example, you apply the upper() function (see Hour 10) to the string values contained in the
list.


Working with Ranges


To close out this topic, there is one other Python data type you’ll run into that can create multiple data
elements. The range data type contains an immutable sequence of numbers that work a lot like a
tuple but are a lot easier to create.


You create a new range value by using the range() method, which has the following format:


range(start, stop, step)

The start value determines the number where the range starts, and the stop value determines
where the range stops (always one less than the stop value specified). The step value determines
the increment value between values. The stop and step values are optional; if you leave them out,
Python assumes a value of 0 for start and 1 for step.


The range data type is a bit odd to work with: You can’t reference it directly, such as to print it out.
You can only reference the individual data values contained in the range, like this:

Free download pdf