Q:

Python program to create a tuple from string and list

0

Example:

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

Create Tuple from String and List in Python

In this article, we will be creating a Python program to create a new tuple of the given string and list in python.

Input:
['Python', 'Programming', 'language']
'Tutorial'

Output: 
('Python', 'Programming', 'language', 'Tutorial')

This task can be performed by adding the values of both collections into a tuple. In Python, there are multiple methods to perform the task.

All Answers

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

Method 1:

One method to solve the problem is by adding the string to the original list as a list and then converting the addition list to a tuple using the tuple() method and print the result.

# Python program to create a tuple 
# from string and list in python

# Initializing and printing the list 
# and string collections
stringList = ["Python", "Programming", "Language"]
apndStr = "Tutorial"
print("The elements of the list : " + str(stringList))
print("The string to be appended is " + apndStr)

# Creating a new tuple ƒrom string 
# and list in Python
apndedTuple = tuple(stringList + [apndStr])

print("The tuple after adding values is : " + str(apndedTuple))

Output:

The elements of the list : ['Python', 'Programming', 'Language']
The string to be appended is Tutorial
The tuple after adding values is : ('Python', 'Programming', 'Language', 'Tutorial')

Method 2:

Another method by performing the tuple conversion of both the collections i.e. string and list. And then concatenate the two tuples.

# Initializing and printing the list 
# and string collections

stringList = ["Python", "Programming", "Language"]
apndStr = "Tutorial"

print("The elements of the list : " + str(stringList))
print("The string to be appended is " + apndStr)

# Creating a new tuple ƒrom string 
# and list in Python
apndedTuple = (apndStr, ) + tuple(stringList)

print("The tuple after adding values is : " + str(apndedTuple))

Output:

The elements of the list : ['Python', 'Programming', 'Language']
The string to be appended is Tutorial
The tuple after adding values is : ('Tutorial', 'Python', 'Programming', 'Language')

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now