0

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

  • `.. for x in ..` is a declaration of x. Granted, there's a reference to `x*x` that happens _before_ the declaration, but that's just the syntax of list comprehensions. You'll get used to it. – John Gordon Feb 02 '23 at 23:49
  • Maybe see this answer too: https://stackoverflow.com/questions/19257862/understanding-for-loops-in-python/19257985#19257985 – beroe Feb 03 '23 at 00:08
  • @beroe That only talks about normal for loops, which I think the OP understands. Their confusion is about generator expressions, which are kind of backwards. – Barmar Feb 03 '23 at 00:20
  • True @Barmar. I figured the other answers/comments explained the correspondence between list comprehension and `for` loops, so added that in case the confusion was more fundamental. – beroe Feb 03 '23 at 00:59
  • @beroe I searched that question for the words "comprehension" and "generator" and didn't find any, so I didn't think it mentioned them. – Barmar Feb 03 '23 at 01:03

1 Answers1

1

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
DJSDev
  • 812
  • 9
  • 18