Search code examples
pythonlistfor-loopenumerate

What does adding a second parameter in a for loop with nested enumerate() do?


I'm trying myself on Python again and I want to create a text-based Ticktacktoe.

Currently, I am working on the layout with 0 representing the empty spaces in the games and numbers up top and on the left for coordinates.This is what I have so far:

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for row in enumerate(game):
    print(row)

which outputs this :

     0  1  2
(0, [0, 0, 0])
(1, [0, 0, 0])
(2, [0, 0, 0])

The problem is that I want it to look like this:

   0  1  2
0 [0, 0, 0]
1 [0, 0, 0]
2 [0, 0, 0]

Now I found a way by adding 'count' into the for loop. But I don't understand why at all. Looking up the Python documentation did not help. Why is this happening? Why does that get rid of the brackets and commas?

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for count, row in enumerate(game):
    print(count, row)

Edit: I think I understand now.Since enumarate() returns the Index and the value all that's basically happening is that I assigned count to the Index and row to basically the value? And that is why there are now brackets since print prints more than 1 variable using a space? Could you confirm this?


Solution

  • In the first example a tuple will be passed to print(), which is printed enclosed in parenthesis. In the second answer the row count and the row itself are passed as separate arguments to print() - print() will then print the arguments space separated.