4

Can someone explain this to me?

import numpy as np

arr = reversed(np.arange(11))

print(list(arr))


print(list(arr))

print(list(arr))

the output of this code is :

enter image description here

why can't I access the arr variable more than once?

Hussain Wali
  • 308
  • 3
  • 12

3 Answers3

3

reversed returns an iterator. When you first call list on it, you iterated on it till the end and it has nothing to give back anymore. So if you call list again, it immediately says "stop iteration" and you get an empty list.

Fix is to store it when you first call list on it:

>>> arr = list(reversed(np.arange(11)))
>>> arr
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Though, in numpy's context you wouldn't cast to list but reverse in numpy domain:

>>> arr = np.arange(11)[::-1]

or

>>> arr = np.arange(10, -1, -1)

or

>>> arr = np.flip(np.arange(11))

or

>>> arr = np.flipud(np.arange(11))

to get

>>> arr
array([10,  9,  8,  7,  6,  5,  4,  3,  2,  1,  0])
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
  • Is there a way of resetting the iterator or are they only one shot objects? – DrBwts Jun 13 '21 at 09:38
  • 1
    @DrBwts One shot yes. Once exhausted (if ever), you need to re-generate. Or you can use something like `itertools.tee` to begin with more than 1 generator. – Mustafa Aydın Jun 13 '21 at 09:39
1

The reversed method

Return a reverse iterator over the values of the given sequence

Once the iterator is consumed, it's empty


If you consume it and store in a list, then you can use it multiple times

import numpy as np

arr = list(reversed(np.arange(11)))
print(list(arr))  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(list(arr))  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(list(arr))  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
azro
  • 53,056
  • 7
  • 34
  • 70
1

This has to do with the return of reversed(). You anticipate that it is a list, but it is an iterator

import numpy as np

arr = reversed(np.arange(11))

>>> print(list(arr))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> print(list(arr))
[]
>>> print(list(arr))
[]

After the firt run, the iterator is empty. You can prevent this by creating a list from the iterator and then print it:

arr2 = list(reversed(np.arange(11)))
>>> print(list(arr2))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> print(list(arr2))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> print(list(arr2))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
user_na
  • 2,154
  • 1
  • 16
  • 36
  • You don't have to convert to `list` in printing out. You converted it in the first line `arr2 = list(reversed(np.arange(11)))` – blazej Jun 13 '21 at 09:06
  • I know, and you are right of cause. I just wanted to use the same print as OP... – user_na Jun 13 '21 at 09:22