-1

I tried this:

myList = [range(1,10)]

print(myList)

and got this output:

range(1, 10)

why it did not returned a list [1,2,3,4,5,6,7,8,9]?

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
mohit kaushik
  • 363
  • 2
  • 13

1 Answers1

2

You are running the example in Python3, where the range function returns an iterable. Therefore, you have to pass the generator to the list function to force the expression to give a full list:

l = list(range(10))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

With a generator, you can iterate over it like so:

 for i in function_that_yields_generator():
       #do something

You can also use the function next() to get elements from a generator. Since the range function is an iterable not an iterator, you can use this:

l = range(10)
new_l = iter(l)
>>next(new_l)
0
>>next(new_l)
1
>>next(new_l)
2

Etc.

For an iterator, you can do this:

>>s = function_that_yields_generator()
>>next(s)
#someval1
>>next(s)
#someval2
Ajax1234
  • 69,937
  • 8
  • 61
  • 102