Python Tuples Cheat Sheet

Posted by

I created a cheat sheet to help when working with common python data types like dictionaries, lists, strings, and tuples.  Knowing how to work with these data types will accelerate your Python development skillset.  I hope you find this useful.

Tuples Data Type

Some important facts to consider when working with tuple datatypes

  • Tuples are immutable (they cannot be changed after creation)
  • Tuples are faster than lists
  • Create tuples by wrapping values in ()
  • A tuple can contain different data types
  • A single tuple can hold duplicate values

Create a tuple

##Create tuple of strings##
names = ('Russ', 'Jon', 'Brent')
print(names)
        
output: ('Russ', 'Jon', Brent')    
    

##Create tuple with mixture of datatypes##
names_and_ages = ('Russ', 45, 'Jon', 46, 'Brent', 35)

#Create tuple with one value#
name = ('Russ',)

Work with values in a Tuple

#Example Tuple#  
names_and_ages = ('Russ', 45, 'Jon', 46, 'Brent', 40)

#print the first element#
print(names_and_ages[0])

output: Russ


#iterate thru tuple and print each value#
for n in names_and_ages:
    print(n)

    output: Russ
            45
            Jon
            46
            Brent
            40

        
##print length of Tuple##        
print(len(names_and_ages))

output: 6

        
##print index location of a desired tuple value##
print(names_and_ages.index('Brent'))

output: 4

Convert datatypes to a Tuple

##Convert string to tuple##
randomstr = "Russ"
newtuple1 = tuple(randomstr)

##Convert list to tuple##
randomlist = [29,'contoso',12,'toys']
newtuple2 = tuple(randomlist)    

##Convert set to tuple##
randomset = {5,6,7,8}
newtuple3 = tuple(randomset)

I created a simple python program to provide these details as help content in addition to other data types.

https://github.com/RussMaxwell/PythonHelper

Python Cheat Sheet Series

Thank You!

Russ Maxwell