Example:
tuple = ("python", "includehelp", 43, 54.23)
Concatenating consecutive elements in tuple
Here, we will be concatenating the current element with the very next element in the tuple and creating a new tuple with the concatenated elements. For this, we will loop over the tuple and concatenate. The resultant tuple will have one less element as the next element to the last element is not present.
Input:
('python', 'programming', 'language', 'learning')
Output:
('python programming', 'programming language', 'language learning')
In Python this task can be easily accomplished using build-it methods present in Python.
Method 1:
One method to solve the problem is by using generator expression to perform the concatenation operation using the zip() method for each element. Then convert the result to a tuple using the tuple() method.
Output:
Method 2:
Another method to solve the problem is by using a lambda function along with a map() to iterate tuple elements and concatenate them. After conversion, convert the resultant collection to a tuple using the tuple() method.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer