Bin(x) in range()


#1

This piece of code:

print(bin(x) for x in range(2, 5))

returns this:

<generator object <genexpr> at 0x7f37509511e0>
None

So I know that range() is an iterator in Python 3, but why is it returning the above in Python 2?
Is that "0x7f37509511e0" a hexadecimal memory address?


#3

Please link to the lesson so we can test.

Your code is creating a generator, which is a valid operation in Python 2.

Python 3

>>> x = (bin(x) for x in range(2, 5))
>>> x
<generator object <genexpr> at 0x02E9E480>
>>> for n in x:
	print (n)

	
0b10
0b11
0b100
>>>

Python 2

 > x = (bin(x) for x in range(2, 5))
 > x
=> <generator object <genexpr> at 0x220fd4>
 > for n in x: 
.. 	print (n) 
.. 	
 0b10
 0b11
 0b100
 >

#5

Yes, in Python 2 range returns a list, and in Python 3 it returns a generator.

x = range(2, 5)    # [2, 3, 4]

However, your code is not just a range. It is very similar to a list comprehension and the way you wrote it makes it a generator.

(x for x in range(2, 5))

The outer parentheses denote a generator in this expression.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.