Create a tuple from string and list – Python

Sometimes, we can have a problem in which we need to construct a new container with elements from different containers. This kind of problem can occur in domains in which we use different types of data. Let’s discuss ways to convert string and list data to tuple.

Method #1 : Using List conversion to tuple + tuple()
In this method, we convert the string to list and then append to target list and then convert this result list to tuple using tuple().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Construct tuple from string and list
# using list conversion to tuple + tuple()
  
# initialize list and string 
test_list = ["gfg", "is"]
test_str = "best"
  
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original string : " + test_str)
  
# Construct tuple from string and list
# using list conversion to tuple + tuple()
res = tuple(test_list + [test_str])
  
# printing result
print("The aggregated tuple is : " + str(res))

chevron_right


Output :

The original list : ['gfg', 'is']
The original string : best
The aggregated tuple is : ('gfg', 'is', 'best')

 

Method #2 : Using Tuple conversion to tuple + tuple()
This is another way in which this task can be performed. In this, we convert the string and list both to tuple and add them to result tuple. This method is more efficient than the above method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Construct tuple from string and list
# using tuple conversion to tuple + tuple()
  
# initialize list and string 
test_list = ["is", "best"]
test_str = "gfg"
  
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original string : " + test_str)
  
# Construct tuple from string and list
# using tuple conversion to tuple + tuple()
res = (test_str, ) + tuple(test_list)
  
# printing result
print("The aggregated tuple is : " + str(res))

chevron_right


Output :

The original list : ['gfg', 'is']
The original string : best
The aggregated tuple is : ('gfg', 'is', 'best')



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.