Q:

Python program for adding a Tuple to List and Vice-Versa

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Adding a Tuple to a list

We have a list of elements and we will be adding a tuple to this list and then returning back a tuple consisting of all elements in a list.

Example:

Input:
myList = [3, 6, 1] , myTuple = (2, 9, 4)

Output:
[3, 6, 1, 2, 9, 4]

We can add a tuple to a list by taking the list and then adding the tuple value using += operator or list.extend() method to add the tuple at the end of our list.

Syntax:

  • += Operator: obj1 += obj2
  • extend() method: list_name.extend(collection)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to add a tuple to a list in Python

# Python program to add a tuple to list 

# Creating the List
myList = [9, 3, 1, 4]

# Printing the List 
print("Initially List : " + str(myList))

# Creating Tuple
myTuple = (2, 6)

# Adding the tuple to list
myList += myTuple

# Printing resultant List
print("List after Addition : " + str(myList))

Output:

Initially List : [9, 3, 1, 4]
List after Addition : [9, 3, 1, 4, 2, 6]

Adding a list to a Tuple

In a similar way as we saw above, we can add a list to a tuple by first converting the tuple to a list then adding the list to it. And then converting the resulting list back to tuple.

Program to add a list to tuple in Python

# Python program to add a tuple to list 

# Creating the List
myTuple = (9, 3, 1, 4)


# Printing the List 
print("Tuple Initially : " + str(myTuple))

# Creating Tuple
myList = [2, 6]

# Adding the tuple to list
addList = list(myTuple)
addList += myList
myTuple = tuple(addList)

# Printing resultant List
print("Tuple after Addition : " + str(myTuple))

Output:

Tuple Initially : (9, 3, 1, 4)
Tuple after Addition : (9, 3, 1, 4, 2, 6)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the maximum and minimum K e... >>
<< Python program to find the size of a tuple...