Eugene Fedotov
Eugene Fedotov

Reputation: 354

Python for loop and arrays

I'm new to python. I'm trying to learn data extracting from an Excel file. I encountered the following statement:

sheet_data = [[sheet.cell_value(r, col) for col in range(sheet.ncols)] for r in range(sheet.nrows)]

I understand regular for loops, but not the below version:

x for y in range()

What does it mean when you have a variable x before the for y in range()?

Upvotes: 1

Views: 152

Answers (3)

COCO
COCO

Reputation: 158

The "x" is an arbitrary variable name that holds the values of the sequence object. Using it in a list comprehension or in a generator expression will return the items in the iterable object that is being stepped through.

Upvotes: 0

timbo
timbo

Reputation: 14324

The for statement is used for looping over a list. This is referred to as an iterator. When it is encompassed by [..], this is referred to as a list comprehension.

List comprehensions allow you to transform one list into another. This is sometimes referred to as a mapping i.e. mapping from X -> Y where a function transforms the value of X into the returned value of Y

So, for example, in

[y + 2 for y in range(...)]

the for is iterating over all values in the list produced by the range(). Each list element has 2 added to each value of y, so the final result is a list where each element is 2 greater than the corresponding element in the source list. Thus, range(3) would produce [0, 1, 2] which then transforms into [2, 3, 4].

So [y for y in range(..)] wouldn't actually accomplish much.

I see that in the example you have provided there are two iterators, which complicates things a bit. But essentially, they are providing two reference variables: r and col, from which the final result is derived using these two variables.

List comprehensions are a very powerful tool in Python. Definitely worth knowing.

Upvotes: 1

David Morton
David Morton

Reputation: 74

These are called list comprehensions in python. If you have a function do_something then the following two blocks are equivalent:

result = [do_something(y) for y in range(10)]

...

result = []
for y in range(10):
    result.append(do_something(y))

Where range(10) could be any iterable.

Think of them as quick ways to create lists. They work for dictionaries too as of python 2.7. This tutorial may be helpful.

Upvotes: 0

Related Questions