0
$\begingroup$

I am new to this whole landscape, please need some hand holding at first, I can't find a beginner section. Can someone please tell me if i is defined inherently in Python. Can i test for this: what type of object is i?

squares=['red', 'yellow', 'green', 'purple', 'blue']

for i, square in enumerate(squares):
    print(i, square)  

Square i is not even defined? There is no programming error.

$\endgroup$
  • $\begingroup$ Welcome to the forum, please make sure you use okay language and code highlighting etc when posting. Cheers! $\endgroup$ – Peter Jul 31 '19 at 11:43
  • 1
    $\begingroup$ This is not a question about data science. This question is better suited for Stack Overflow. $\endgroup$ – kbrose Jul 31 '19 at 12:45
3
$\begingroup$

No, i is not predefined. If you use enumarate(), i (or whatever you may call it) is a count: see the docs.

squares=['red', 'yellow', 'green', 'purple', 'blue']

for i, square in enumerate(squares):
    print(i, square) 

Gives you:

0 red
1 yellow
2 green
3 purple
4 blue

You can also set a start value for the count (Python by default starts counting by 0):

for i, square in enumerate(squares,10):
    print(i, square) 

Gives you:

10 red
11 yellow
12 green
13 purple
14 blue

In case you just want to loop over a list, you can write:

for i in squares:
    print(i)

Which gives you:

red
yellow
green
purple
blue
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.