"Tuples" comprehension | Sololearn: Learn to code for FREE!

0

"Tuples" comprehension

I can make a list comprehension. But when I try to make a Tuples comprehension code don't give me an error. Code give me: <generator object <genexpr> at 0x739e4e4ac0> What is it? Can I make a working Tuples comprehension? P.S Tuples comprehension it is like tpl = (x*2 for x in range(3))

6/21/2021 5:41:29 PM

Ласковый Зверёк

4 Answers

New Answer

+5

That question is answered better here than I could've done. https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python#16940351

+4

Andrew Choi Interestingly, it's almost twice as fast using tuple([list comprehension]) than using tuple(generator) per Slick ' s reference: Tuple from list comprehension: $ python3 -m timeit "a = tuple([i for i in range(1000)])" 10000 loops, best of 3: 30.2 usec per loop Tuple from generator: $ python3 -m timeit "a = tuple(i for i in range(1000))" 10000 loops, best of 3: 50.4 usec per loop

+2

in addition to what Slick provided. i believe the code you provided is called a generator. and from what i understand is that generators do not store the object in memory. it is used as an alternative for when a list is extremely long (100K+) for performance reasons. for a tuple, you could add “tuple” right before the paranthesis like below. it is also the solution from the link. tpl = tuple(x*2 for x in range(3))

+1

David Ashton that is interesting.