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))

21st Jun 2021, 5:41 PM
Š›Š°ŃŠŗŠ¾Š²Ń‹Š¹ Š—Š²ŠµŃ€Ń‘Šŗ
Š›Š°ŃŠŗŠ¾Š²Ń‹Š¹ Š—Š²ŠµŃ€Ń‘Šŗ - avatar
4 Answers
21st Jun 2021, 5:45 PM
Slick
Slick - avatar
+ 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
22nd Jun 2021, 5:35 AM
David Ashton
David Ashton - avatar
+ 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))
21st Jun 2021, 6:03 PM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 1
David Ashton that is interesting.
22nd Jun 2021, 11:10 AM
you are smart. you are brave.
you are smart. you are brave. - avatar