prettywack
prettywack

Reputation: 1

Why don't we have to declare the variable in this python for loop?

So I'm learning Python and I'm slowly picking up the pieces. I'm taking a practice quiz and I sadly had to go to stackoverflow to solve it. I tried to disassemble the code and saw it has x variables in the for loop, which are never declared/referenced in the code.

Is there an explanation / rule of thumb for when I need to initialize these variables? I notice I sometimes don't get errors when I don't declare and sometimes I do. Maybe I'm misunderstanding (I'm really misunderstanding).

def squares(start, end):
    return [ x*x for x in range(start,end+1) ] # Create the required list comprehension.


print(squares(2, 3)) # Should print [4, 9]

enter image description here

Upvotes: 0

Views: 49

Answers (1)

DJSDev
DJSDev

Reputation: 993

The x in the loop statement is the declaration of the variable. Essentially, think of it the same as a for loop

# x is declared here and used within the block
for x in range(0, 10):
    print(x)

In a list comprehension (what you're looking at), it's the same except it's shifted a little to the right.

[ x*x for x in range(0,10) ]
          ^ declaration

Upvotes: 1

Related Questions