Tuple Comprehension
Rushikesh J.
QA Automation Engineer @Vinz Global | Robot Framework | Manual Testing, Automation Testing | Python | Selenium | GIT | JIRA | Immediate Joiner | API Testing Using Postman | Jenkins
What is comprehension
?We create a sequence from a given sequence is called comprehension
?Sequence means list, tuple, string and range
?Some sequence allow comprehension but some not
Why we need of Comprehension?
?Filtering & Searching
?Creating a new sequence on the basis of some condition
?Simple way to create new sequence
?Fastest way
?One line of code
?We cannot work with tuple comprehension in Python.
?For Comprehension, we need to use of loop or iterating over sequence elements / items to get or store in new variable or container.
?But with tuple, we cannot do that, because tuple did not support updation.
?As tuple is immutable object
Anyhow syntax:
newSeq = [expression for item/element in sequence]
Comprehension example
Example:
t1 = (1,2,3,4,11,10,20,41,15)
t2 = (i for i in t1 if i%4 == 0)
print(t2) # you will get a generator object
What is generator object?
?Used to create iterators
?It return a iterator
?it can iterate that give one value at time
?To get next value we used special method that next()
Is it possible comprehension with tuple?
No, because
?It is limited
?It become complex
?It is immutable
?It return generator object