Merge a tuple and a list into a single list in Python

In this tutorial, you will learn how to merge a tuple and a list into a single list in Python.

For this, first, let us make a list in Python. The list can contain anything in Python no matter whether it is an integer or a string. We are going to call our list as “sample_list” in this tutorial.

sample_list = [1,2,3,'four']

Now we will create a sample tuple and as we know tuples can be created just like lists, the only difference is that we use parenthesis instead of square brackets.

sample_tuple = (5,6,7,'eight')

Now, as we all know that if you want to add up two or more elements in Python, then they should be of the same data type. You will do the same here, you can not add a tuple to a list using the “+” operator, if you try to do so you will get an error and to avoid that error you have to convert the tuple into the list and vice-versa.

Python program to merge a tuple and a list into a single list

Now in order to convert a tuple into a list you have to convert the current tuple into a list and we can do that by using the list() method and the code for the same is:

converted_tuple = list(sample_tuple)

This will convert the “sample_tuple” into a list with the same elements and we have stored it in a variable called converted_tuple. Now, we can simply use the “+” operator to add a list to another list, or a tuple to another tuple and code for the same is:

resulting_list = sample_list + converted_tuple
print(resulting_list)

And the output for the above code will be:

[1, 2, 3, 'four', 5, 6, 7, 'eight']

In this way, we can merge a tuple and a list into a single list in Python.

Note:- ¬†We can convert a list into a tuple by using the same method as above, but in this case, we use tuple() method in place of list() and we pass the list as a parameter. It will just convert the list into a tuple and then you can add both the tuple by using the “+” operator.

Leave a Reply

Your email address will not be published. Required fields are marked *