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.
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
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.
Example 4
Python's built-in sum() function also helps in concatenating tuples. We use an expression
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.
Example 5
A slightly complex approach for merging two tuples is using list comprehension, as following code shows −
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