python logo

convert to tuple python


Python hosting: Host, run, and code Python in the cloud!

The tuple is a fundamental data structure in Python, characterized by its immutability and ability to hold multiple, ordered items. This makes it suitable for use cases where data integrity is essential, and once set, it shouldn’t be changed.

In Python, a tuple can be constructed using parentheses. For instance:

personInfo = ("Diana", 32, "New York")

If you’re keen to dive deeper into Python, you might be interested in the following course:
Python Programming Bootcamp: Go from zero to hero.

Converting Lists to Tuples in Python

Lists in Python are mutable, meaning their contents can be changed after creation. If you need to convert a list into a tuple for immutability, the tuple() function comes in handy.

#!/usr/bin/env python
listNumbers = [6,3,7,4]
x = tuple(listNumbers)
print(x)

Transforming Tuples into Lists

To transform a tuple into a list, enabling item modifications, use the list() function.

#!/usr/bin/env python
x = (4,5)
listNumbers = list(x)
print(listNumbers)

Converting a Tuple to a String

For tuples consisting solely of strings, a seamless conversion to a single string can be achieved using the join() method.

#!/usr/bin/env python
person = ('Diana','Canada','CompSci')
s = ' '.join(person)
print(s)

Sorting a Tuple in Python

A unique property of tuples is their immutability. So, while they lack an inherent sort method, there’s a workaround. You can employ the sorted() function, which outputs a list. Then, turn this list back into a tuple.

#!/usr/bin/env python
person = ('Alison','Victoria','Brenda','Rachel','Trevor')
person = tuple(sorted(person))
print(person)

Bear in mind, since a tuple’s contents can’t be altered, this method essentially constructs a new, sorted tuple.

Continue to the Next Topic






Leave a Reply: