Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no tuple comprehension in Python?

As we all know, there's list comprehension, like

[i for i in [1, 2, 3, 4]] 

and there is dictionary comprehension, like

{i:j for i, j in {1: 'a', 2: 'b'}.items()} 

but

(i for i in (1, 2, 3)) 

will end up in a generator, not a tuple comprehension. Why is that?

My guess is that a tuple is immutable, but this does not seem to be the answer.

like image 332
Shady Xu Avatar asked Jun 05 '13 12:06

Shady Xu


People also ask

Can you do list comprehension on a tuple?

We can perform comprehension to sequences such as lists, sets, dictionaries but not to tuples.

Is tuple comprehension faster than list comprehension?

the choice between tuple or list is based on what you are planning on doing with it and not resources. Apart from the overhead of the conversion, the tuple will be smaller and faster, since it lacks the mechanism to make it mutable, allow fast inserts etc.

Why are tuples not listed?

The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.

Is there a tuple function in Python?

The Python tuple() function is a built-in function in Python that can be used to create a tuple. A tuple is an ordered and immutable sequence type.


1 Answers

You can use a generator expression:

tuple(i for i in (1, 2, 3)) 

but parentheses were already taken for … generator expressions.

like image 114
Martijn Pieters Avatar answered Oct 19 '22 03:10

Martijn Pieters