Basically many people will argue that there is no such thing as a tuple comprehension because it will return some gibberish output, but the fact is there is tuple comprehension which is efficient than list comprehension.
For example, if we take list comprehension by executing the below code you will get output like
x=[i**2 for i in range(10)]
print(x)[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
If we try the same code in tuple we will get something like this,
x=(i**2 for i in range(10))
print(x)generator object <genexpr> at 0x7f4863bf77d0>
This output is nothing but a generator.
what is a generator?
They are just like a list comprehension, but it doesn’t store its values on the memory, it only generates the value you are iterating on when the generator is called.
To check for a value on a generator you can either iterate over the generator using a for loop or you can check the values using the next() operator.
t=(i**2 for i in range(10))#accessing through the next operator
0 #returns the first element of the tuple
1 #returns the second element of the tuple
By using the next() function you can check all the values till the last one, if you want to check it all at once you can also iterate through the for operator.
t=(i**2 for i in range(10))
for i in t:
Is tuple comprehension is efficient than list comprehension?
yes, tuple comprehension is efficient. In list, it stores all the elements in the memory and it consumes a lot of memory but when it comes to tuple it only stores the element which is called upon so it is memory efficient.
x = [i**2 for i in range(10000)] #list
print(sys.getsizeof(x))87632y = (i**2 for i in range(10000)) #tuple
If we take a similar list and tuple and check its size by sys.getsizeof( ) we can see that tuple is consuming lesser memory than the list.