Program to add tuple to list and vice – versa using Python

Introduction

Given the two containers list and tuple with some number of elements, the task is to perform the addition of containers and return the output.

Program to add tuple to list and vice – versa using Python

Program

Approach 1

from itertools import chain, product
ip_list = [7, 11]
ip_tuple = (5, 6, 1)
# Using += operator
ip_list += ip_tuple
print("Output : ", ip_list)

Output:

Program to add tuple to list and vice – versa using Python Output 1

Approach 2

ip_list = [1, 2, 3]
ip_tuple = (4, 5)
# Using tuple(), data type conversion [tuple + list]
output = tuple(list(ip_tuple) + ip_list)
print("The container after addition: " + str(output))

Output:

Program to add tuple to list and vice – versa using Python Output 2

Explanation

In the first approach, we have used += operator to join the given list to tuple. Its functionality is similar to that of list.extend() which takes argument of any type.

In the second approach, we have used tuple() to add the given list to tuple. In this approach, the given tuple is first converted to list and then added to the given list. The final output is then converted to tuple and printed on the screen.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.