Open In App

Python – Concatenate Tuple elements by delimiter

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tuple, concatenate each element of tuple by delimiter.

Input : test_tup = (“Gfg”, “is”, 4, “Best”), delim = “, ” 
Output : Gfg, is, 4, Best 
Explanation : Elements joined by “, “. 

Input : test_tup = (“Gfg”, “is”, 4), delim = “, ” 
Output : Gfg, is, 4 
Explanation : Elements joined by “, “.

Method #1 : Using list comprehension

In this, we iterate for each element in tuple using loop in list comprehension and concatenate using + operator.

Python3




# Python3 code to demonstrate working of
# Concatenate Tuple elements by delimiter
# Using list comprehension
 
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing delim
delim = "-"
 
# using str() to convert elements to string
# join to convert to string
res = ''.join([str(ele) + delim for ele in test_tup])
 
# striping stray char
res = res[ : len(res) - len(delim)]
 
# printing result
print("Concatenated Tuple : " + str(res))


Output

The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Time complexity: O(n), where n is the number of elements in the tuple.
Auxiliary space: O(n), where n is the number of elements in the tuple.

Method #2 : Using join() + map()

In this, we convert all chars to string using str() and map to perform str() to all elements, then concatenation using join().

Python3




# Python3 code to demonstrate working of
# Concatenate Tuple elements by delimiter
# Using join() + map()
 
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing delim
delim = "-"
 
# for joining, delim is used
res = delim.join(map(str, test_tup))
 
# printing result
print("Concatenated Tuple : " + str(res))


Output

The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Time complexity: O(n), where n is the number of elements in the tuple. 
Auxiliary space: O(m), where m is the length of the resulting string. 

Method #3: Using loop

This program takes a tuple as input and concatenates its elements with a given delimiter using a loop. It then strips the last delimiter from the resulting string and prints it.

Python3




# Python3 code to demonstrate working of
# Concatenate Tuple elements by delimiter
# Using loop
 
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing delim
delim = "-"
 
# initializing result string
res = ""
 
# using loop to concatenate elements with delimiter
for ele in test_tup:
    res += str(ele) + delim
 
# striping stray char
res = res[ : len(res) - len(delim)]
 
# printing result
print("Concatenated Tuple : " + str(res))


Output

The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Time complexity: O(n), where n is the length of the input tuple test_tup.
Auxiliary space: O(n), where n is the length of the input tuple test_tup.

Method #4: Using join() + generator expression

Use the join() method and a generator expression to convert each element of the tuple to a string and concatenate them with the delimiter. Finally, it prints the original tuple and the concatenated string.

Step-by-step approach:

  • Create a generator expression that converts each element of the tuple to a string and yields it.
  • Use the join() method to concatenate the strings in the generator expression with the delimiter.
  • Print the concatenated string.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Concatenate Tuple elements by delimiter
# Using join() + generator expression
 
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing delimiter
delim = "-"
 
# using join() + generator expression to concatenate elements with delimiter
res = delim.join(str(ele) for ele in test_tup)
 
# printing result
print("Concatenated Tuple : " + str(res))


Output

The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Time complexity: O(n), where n is the number of elements in the tuple.
Auxiliary space: O(n), where n is the number of elements in the tuple (used by the generator expression).

Method#5: Using Recursive method.

Algorithm:

  1. Define a function that takes the tuple, delimiter, and two optional variables i and res as input parameters.
  2. In the function, check for the base case where the index variable i equals to the length of the tuple minus one, return the concatenated result string plus the last element of the tuple converted to string using str().
  3. If the base case is not reached, then we concatenate the current tuple element to the result string variable and add the delimiter.
  4. Call the recursive function with the next index value and the updated result string variable.
  5. Return the recursive function call.

Python3




# Python3 code to demonstrate working of
# Concatenate Tuple elements by delimiter
def concatenate_tuple_recursive(test_tup, delim, i=0, res=""):
    # base case
    if i == len(test_tup) - 1:
        return res + str(test_tup[i])
     
    # recursive case
    res += str(test_tup[i]) + delim
    return concatenate_tuple_recursive(test_tup, delim, i+1, res)
 
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing delim
delim = "-"
 
res = concatenate_tuple_recursive(test_tup, delim)
 
 
# printing result
print("Concatenated Tuple : " + str(res))


Output

The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Time complexity: O(n), where n is the length of the tuple, because we are calling the recursive function once for each element in the tuple.
Space complexity: O(n), because we are using the recursive function call stack to store the function calls until we reach the base case, which can be up to the length of the tuple.

Method#6: reduce function from the functools module.

 Algorithm:

  1. Import the reduce function from the functools module.
  2. Create a tuple test_tup with the elements “Gfg”, “is”, 4, and “Best”.
  3. Initialize a delimiter delim with the value “-“.
  4. Apply the reduce function to the test_tup tuple with a lambda function that takes two arguments x and y, converts them to strings using the str function, concatenates them with the delimiter using the + operator, and returns the result.
  5. The reduce function applies the lambda function to the first two elements of test_tup, then applies it to the result and the third element, and so on, until all elements of test_tup have been processed. The final result is a string with all elements of the tuple concatenated with the delimiter.
  6. Print the original tuple and the concatenated tuple using the print function.

Python3




from functools import reduce
 
test_tup = ("Gfg", "is", 4, "Best")
delim = "-"
 
res = reduce(lambda x, y: str(x) + delim + str(y), test_tup)
 
print("The original tuple is : " + str(test_tup))
print("Concatenated Tuple : " + str(res))
#This code is contributed by Jyothi pinjala


Output

The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Time Complexity:

The time complexity of the given code is O(n), where n is the number of elements in the tuple test_tup. This is because the reduce function applies the lambda function to each element of test_tup exactly once, resulting in a linear time complexity.
Space Complexity:

The space complexity of the given code is O(n), where n is the number of elements in the tuple test_tup. This is because the reduce function creates a new string for each concatenation, resulting in a linear space complexity. However, since the input tuple is not modified, the space complexity of the input is not considered.

Method #7 : Using itertools.chain() and itertools.islice()

Step-by-step approach:

  • Import the itertools module and the chain() and islice() functions.
  • Initialize the tuple and the delimiter.
  • Use chain() function to concatenate the first two elements of the tuple with the rest of the elements.Use islice() function with map() to convert the rest of the elements to strings.
  • Join the sliced and mapped elements with the delimiter.
  • Print the concatenated tuple.

Python3




from itertools import chain, islice
 
test_tup = ("Gfg", "is", 4, "Best")
delim = "-"
 
result = delim.join(chain(islice(test_tup, 0, 2), map(str, islice(test_tup, 2, None))))
 
print("Concatenated Tuple : " + result)


Output

Concatenated Tuple : Gfg-is-4-Best

The time complexity of this method is O(n), where n is the number of elements in the tuple.
The auxiliary space complexity of this method is also O(n), where n is the number of elements in the tuple. 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads