Q:

Python program to concatenate consecutive elements in tuple

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

# Python program to concatenate consecutive
# elements in tuple

# initialising and printing tuple 
myTuple = ("python ", "programming ", "language ", "tutorials ")
print("The elements of initial Tuple are "+str(myTuple))

# Concatenating consecutive elements in the tuple  
concatTuple = tuple(i + j for i, j in zip(myTuple, myTuple[1:]))
  
# printing Resultant tuple  
print("The elements of tuple created by concatenating consecutive elements are "+str(concatTuple))

Output:

The elements of initial Tuple are ('python ', 'programming ', 'language ', 'tutorials ')
The elements of tuple created by concatenating consecutive elements are ('python programming ', 'programming language ', 'language tutorials ')

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.

# Python program to concatenate 
# consecutive elements in tuple

# initialising and printing tuple 
myTuple = ("python ", "programming ", "language ", "tutorials ")
print("The elements of initial Tuple are "+str(myTuple))

# Concatenating consecutive elements in the tuple  
concatTuple = tuple(map(lambda i, j : i + j, myTuple[: -1], myTuple[1: ]))
  
# printing Resultant tuple  
print("The elements of tuple created by concatenating consecutive elements are "+str(concatTuple))

Output:

The elements of initial Tuple are ('python ', 'programming ', 'language ', 'tutorials ')
The elements of tuple created by concatenating consecutive elements are ('python programming ', 'programming language ', 'language tutorials ')

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now