When it is required to concatenate two string tuples, the 'zip' method and the generator expression can be used.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
Below is a demonstration of the same −
Example
my_tuple_1 = ('Jane', 'Pink', 'El') my_tuple_2 = ('Will', 'Mark', 'Paul') print ("The first tuple is : " ) print(my_tuple_1) print ("The second tuple is : " ) print(my_tuple_2) my_result = tuple(elem_1 + elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2)) print("The concatenated tuple is : ") print(my_result)
Output
The first tuple is : ('Jane', 'Pink', 'El') The second tuple is : ('Will', 'Mark', 'Paul') The concatenated tuple is : ('JaneWill', 'PinkMark', 'ElPaul')
Explanation
- Two list of tuples (strings) are defined, and displayed on the console.
- The lists are iterated over, and they are zipped using the 'zip' method.
- The first and second elements from both the list of tuples are added/concatenated.
- This is then converted to a tuple.
- This operation is assigned to a variable.
- This variable is the output that is displayed on the console.