Convert tuple
The tuple data structure is used to store a group of data. The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.
An example of a tuple would be:
personInfo = ("Diana", 32, "New York")
Convert list to a tuple
To convert a list to a tuple you can use the tuple() function.#!/usr/bin/env python
listNumbers = [6,3,7,4]
x = tuple(listNumbers)
print(x)
Convert tuple to list
You can convert an existing tuple to a list using the list() function:#!/usr/bin/env python
x = (4,5)
listNumbers = list(x)
print(listNumbers)
Convert tuple to string
If your tuple contains only strings (text) you can use:#!/usr/bin/env python
person = ('Diana','Canada','CompSci')
s = ' '.join(person)
print(s)
Sort a tuple
Tuples are arrays you cannot modify and don't have any sort function.But, there is a way. You can however use the sorted() function which returns a list. This list can be converted to a new tuple.
#!/usr/bin/env python
person = ('Alison','Victoria','Brenda','Rachel','Trevor')
person = tuple(sorted(person))
print(person)
Keep in mind a tuple cannot be modified, we simple create a new tuple that happens to be sorted.
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises