0

When I used for loop to iterate object

arr = map(int, input().split())

for j in arr: # this print's results
    print(j)

for i in arr: # this doesn't print any results
    print(i)

On the other hand

any = [5,8,6,4]

for i in any:  # this print's results
    print(i)

for j in any: # this also print's results
    print(j)

Why for iterating the object file it doesn't prints result for the second time. Can any one help?

llinvokerl
  • 1,029
  • 10
  • 25
  • What is the type of arr in the first case? If it is an iterator you can only iterate over it once. In the second case it is a list that has an `__iter__` method, so you can iterate over it repeatedly. Try wrapping map in list – Scott Skiles Dec 31 '19 at 02:54
  • See this: https://stackoverflow.com/questions/25336726/why-cant-i-iterate-twice-over-the-same-data – Scott Skiles Dec 31 '19 at 02:56

3 Answers3

0

It's likely in this case that input().split() is a generator object. Generator objects can only be used once. Using the example generator function from this stackover flow post we can reproduce your issue

# Create generator function
def generator(n):
  a = 1

  for _ in range(n):
    yield a
    a += 1

# Set vars
a = [1 ,2, 3, 4]
b = generator(4)

## type(a) ->  list
## type(b) -> generator

# Print each var

# First time through list a
for i in a:
  print(i)
## prints 1, 2, 3, 4

# First time through list b
for i in b:
  print(i)
## prints 1, 2, 3, 4

# Second time through list a
for i in a:
  print(i)
## prints 1, 2, 3, 4

# Second time through list b
for i in b:
  print(i)

# Prints nothing

You may be able to fix this by converting input().split() into a list. i.e list(input().split())

Alexis Lucattini
  • 1,211
  • 9
  • 13
0

I don't know exactly what is the reason behind it, i guess it might be related to iterators, i've had this problem for a long time, one of the solutions i use most of the time is to convert the result of map to list, like :

arr = list(map(int, input().split()))

for j in arr: # this will print the results
    print(j)

for i in arr: # this also will print the results
    print(i)
Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25
0

According to Python 3 documents, map() returns an iterator. You can only consume iterator once.

See similar question Python - Printing Map Object Issue

graffaner
  • 145
  • 7