89DEVs

Python How to: Tuple to list of strings conversion

Tuple to list conversion

How to convert a tuple to a list in Python? Use the list() function in Python to convert the tuple to a list. The difference between tuples and lists is that the values of a tuple can not be changed. If you want to change the values of the tuple, it is possible to convert the tuple to a list, make the changes and then convert the list back to a tuple if necessary.

convert Tuple to list

To convert a Tuple to a list of strings, use the list() function. # convert Tuple to List myTuple = ('a', 'b', 'c') myList = list(myTuple) print(myList) The Tuple has been converted to a list of strings and is returned. ['a', 'b', 'c']

append Tuple to List

To append a tuple to a list, use the list.append() method or list.extend method. The difference is that the append() method appends the whole tuple. While the extend() method extends the list by the tuple elements. To append the whole tuple as tuple to an existing list, use the append() method: ['a', 'b', 'c', ('d', 'e', 'f')] To append the elements of a tuple to an existing list, use the extend() method: ['a', 'b', 'c', 'd', 'e', 'f']

list.append() method

# append Tuple to List using list.append() function myTuple = ('d', 'e', 'f') myList = ['a', 'b', 'c'] myList.append(myTuple) print(myList) The Tuple is now appended as a tuple. ['a', 'b', 'c', ('d', 'e', 'f')]

list.extend() method

# append Tuple to List using list.extend() function myTuple = ('d', 'e', 'f') myList = ['a', 'b', 'c'] myList.extend(myTuple) print(myList) The elements of the tuple are now appended as list elements. ['a', 'b', 'c', 'd', 'e', 'f']

Reverse: List of strings to tuple

To reverse the list to a tuple use the the tuple() function. # list of string to tuple my_list = ['a', 'b', 'c'] my_tuple = tuple(my_list) print(my_tuple) The list is turned into a tuple. To confirm the type of the returned object, use the type() function. ('a', 'b', 'c')

List of tuples into list

In case we have a list of tuples to convert, use list comprehensions to join the items in the list. # list of tuples to list my_tuple_list = [('this', 'is'), ('the', 'reality')] my_list = [' '.join(item) for item in my_tuple_list] print(my_list) A list of strings is returned. ['this is', 'the reality']

                
        

Summary


Click to jump to section