Join tuple in Python

The Join tuple in Python can be used operator ( + ) or ( * ) to connect two tuples or more tuples. In Python, you cannot directly “join” tuples in the same way you can join strings or lists using the join() method. However, you can concatenate tuples to create a new tuple.

Using plus operator (+ ) to join tuple elements in Python

We will create tuple myCar1, inside myCar1 contains the range of car’s brand such as Toyota, Mitsubishi, and Honda.After that, we will create another tuple myCar2 which contains the range of the other car’s brand. Then, we will join these tuples together. The output will be Toyota , Mitsubishi. Honda, Volvo, BMW.

Let’s see the code example below:

myCar1=('Toyota','Mitsubishi','Honda' )
myCar2=('Volvo','BMW')
myCar=myCar1+ myCar2
print(myCar)
#output: ('Toyota', 'Mitsubishi', 'Honda', 'Volvo', 'BMW')
Using multiply operator ( *) to join tuple in Python

Using multiply operator * is different from + operator because we need to multiply with a number to what the tuple is currently hold. So the current value in tuple will extend to the number that you multiply. For example , if we have the tuple with contain the item ‘A’, ‘B’,’C’ , and then you want to multiply with 2. As the result, this current tuple will be ‘A’, ‘B’,’C’ , ‘A’, ‘B’,’C’.

For example:

myCar1=('Toyota','Mitsubishi' )
myCar=myCar1*3
print(myCar)
#output: ('Toyota', 'Mitsubishi', 'Toyota', 'Mitsubishi', 'Toyota', 'Mitsubishi')
 

The example above shows that myCar1 that contains (‘Toyota’,’Mitsubishi’ ), then it’s extended 3 times of the current tuple with the same value.

freecode4learn.com

Leave a Reply