Home > Enterprise >  enumerate does not work with 2d arrays yet range(len()) doea
enumerate does not work with 2d arrays yet range(len()) doea

Time:06-15

I heard somewhere that we should all use enumerate to iterate through arrays but

for i in enumerate(array):
    for j in enumerate(array[i]):
        print(board[i][j])

doesn't work, yet when using range(len())

for i in range(len(array)):
    for j in range(len(array[i)):
        print(board[i][j])

it works as intended

CodePudding user response:

use it like this:

for idxI, arrayI in enumerate(array):
    for idxJ, arrayJ in enumerate(arrayI):
        print(board[idxI][idxJ])

CodePudding user response:

Like I wrote enumerate adds an extra counter to each element. Effectively turning you list of elements into a list of tuples.

Example

array = ['a', 'b','c','d']
print(list(enumerate(array)))

gives you this:

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

So in your case what you want to do it simply add the extra element when iterating over it

for i, item1 in enumerate(array):
    for j,item2 in enumerate(array[i]):
        print(array[i][j])

Issue was in your case is

for i in enumerate(array):

this i is not an integer but a tuple ('1','a') in my case. And you cant access a list element with an index value of a tuple.

CodePudding user response:

When one uses for i in enumerate(array): it returns a collection of tuples. When working with enumerate, the (index, obj) is returned while range based loops just go through the range specified.

>>> arr = [1,2,3]
>>> enumerate(arr)
<enumerate object at 0x105413140>
>>> list(enumerate(arr))
[(0, 1), (1, 2), (2, 3)]
>>> for i in list(enumerate(arr)):
...     print(i)
... 
(0, 1)
(1, 2)
(2, 3)
>>> 

One has to access the first element of the tuple to get the index in order to further index.

>>> board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> for idx1,lst in enumerate(board):
...     for idx2,lst_ele in enumerate(lst): # could use enumerate(board[i])
...             print(lst_ele,end=" ")
... 
1 2 3 4 5 6 7 8 9
>>>

Sometimes you do not need both the index and the element so I do not think its always better to use enumerate. That being said, there are plenty of situations where its easier to use enumerate so you can grab the element faster without having to write element = array[idx].

See range() vs enumerate()

"Both are valid. The first solution [range-based] looks more similar to the problem description, while the second solution [enum-based] has a slight optimization where you don’t mutate the list potentially three times per iteration." - James Uejio

  • Related