In Python, a tuple is an immutable sequence of objects. Concatenation is the process of joining two or more tuples into a single tuple. In this article, we'll explore different ways to concatenate tuples in Python.
The + operator can be used to concatenate two tuples. Here is an example:
tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) tuple3 = tuple1 + tuple2 print(tuple3)
Output:
(1, 2, 3, 4, 5, 6)
In this example, we first created two tuples tuple1
and tuple2
with some values. We then used the + operator to concatenate them into tuple3
.
The * operator can be used to concatenate multiple copies of a tuple. Here is an example:
tuple1 = (1, 2, 3) tuple2 = tuple1 * 2 print(tuple2)
Output:
(1, 2, 3, 1, 2, 3)
In this example, we first created a tuple tuple1
with some values. We then used the * operator to create a new tuple tuple2
that contains two copies of tuple1
.
The extend() method can be used to append one tuple to another. Here is an example:
tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) list1 = list(tuple1) list2 = list(tuple2) list1.extend(list2) tuple3 = tuple(list1) print(tuple3)
Output:
(1, 2, 3, 4, 5, 6)
In this example, we first created two tuples tuple1
and tuple2
with some values. We then converted them into lists using the list() function. We used the extend() method to append list2
to list1
. Finally, we converted the resulting list back into a tuple tuple3
.
The itertools module provides a chain() function that can be used to concatenate multiple tuples. Here is an example:
import itertools tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) tuple3 = (7, 8, 9) tuple4 = tuple(itertools.chain(tuple1, tuple2, tuple3)) print(tuple4)
Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9)
In this example, we first imported the itertools module. We then created three tuples tuple1
, tuple2
, and tuple3
with some values. We used the chain() function to concatenate these tuples into tuple4
.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.