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 :
why can't I access the arr variable more than once?
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 :
why can't I access the arr variable more than once?
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])
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]
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]