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

(singke) #1
>>> range1 = range(5)
>>> print(range1)
range(0, 5)
>>> print(range1[2])
2
>>> for x in range1:
print(x)

0
1
2
3
4
>>>

When you try to print the range1 variable, Python just returns the range object, showing the
start and stop values. However, you can print the range1[2] value, which references the third
data value in the range.


The range data type comes in most handy in the for statement, as shown in the preceding example.
You can easily iterate through a range of values in the for loop by just specifying the range.


Watch Out!: The range() Change
In Python v2, the range() function created a sequence of numbers as a standard list
data type. Python v3 changed that to make the range data type separate from the
list data type. Be careful if you run into any v2 code that assumes that range is
list!

Summary


In this hour, you took a look at the tuple and list data types in Python. Tuples allow you to reference
multiple data values using a single variable. Tuple values are immutable, so once you create a tuple,
you can’t change it in your program code. Lists also contain multiple data values, but you can change,
add, and delete values in lists. Python supports lots of functions to help you manipulate data using
lists. They come in handy when you need to iterate through a data set of values in your scripts. List
comprehensions allow you to create new lists based on values in another list, a tuple, or a range of
values. You can define complex equations to manipulate the data as Python transfers it using a list
comprehension, making it a very versatile tool in Python.


In the next hour, we’ll turn our attention to yet another type of data storage in Python, using
dictionaries and sets.


Q&A


Q. Can you use lists to perform matrix arithmetic?
A. Not easily. Python doesn’t have any built-in functions that can perform mathematical
operations on list data values directly. You’d have to write your own code to iterate through
the individual list values and perform the calculations.
Fortunately, there’s the NumPy module (see Hour 5, “Using Arithmetic in Your Programs”),
Free download pdf