Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

In Python, a Tuple is classified as a sequence type object. It is a collection of items, which may be of different data types, with each item having a positional index starting with 0. Although this definition also applies to a list, there are two major differences in list and tuple. First, while items are placed in square brackets in case of List (example: [10,20,30,40]), the tuple is formed by putting the items in parentheses (example: (10,20,30,40)).

In Python, a Tuple is an immutable object. Hence, it is not possible to modify the contents of a tuple one it is formed in the memory.

However, you can use different ways to join two Python tuples.

Example 1

All the sequence type objects support concatenation operator, with which two lists can be joined.

 
T1 = (10,20,30,40) T2 = ('one', 'two', 'three', 'four') T3 = T1+T2 print ("Joined Tuple:", T3)

It will produce the following output −

Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')

Example 2

You can also use the augmented concatenation operator with the "+=" symbol to append T2 to T1

 
T1 = (10,20,30,40) T2 = ('one', 'two', 'three', 'four') T1+=T2 print ("Joined Tuple:", T1)

Example 3

The same result can be obtained by using the extend() method. Here, we need cast the two tuple objects to lists, extend so as to add elements from one list to another, and convert the joined list back to a tuple.

 
T1 = (10,20,30,40) T2 = ('one', 'two', 'three', 'four') L1 = list(T1) L2 = list(T2) L1.extend(L2) T1 = tuple(L1) print ("Joined Tuple:", T1)

Example 4

Python's built-in sum() function also helps in concatenating tuples. We use an expression

sum((t1, t2), ())

The elements of the first tuple are appended to an empty tuple first, and then elements from second tuple are appended and returns a new tuple that is concatenation of the two.

 
T1 = (10,20,30,40) T2 = ('one', 'two', 'three', 'four') T3 = sum((T1, T2), ()) print ("Joined Tuple:", T3)

Example 5

A slightly complex approach for merging two tuples is using list comprehension, as following code shows −

 
T1 = (10,20,30,40) T2 = ('one', 'two', 'three', 'four') L1, L2 = list(T1), list(T2) L3 = [y for x in [L1, L2] for y in x] T3 = tuple(L3) print ("Joined Tuple:", T3)

Example 6

You can run a for loop on the items in second loop, convert each item in a single item tuple and concatenate it to first tuple with the "+=" operator

 
T1 = (10,20,30,40) T2 = ('one', 'two', 'three', 'four') for t in T2: T1+=(t,) print (T1)
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Hjälpte svaret dig? 1 användare blev hjälpta av detta svar (1 Antal röster)