3️⃣

17.3 Tuple Basics

Tuple Basics

There are a couple of ways to initialize an empty tuple:

tup = tuple()  # creates an empty tuple
tup = ()  # also creates an empty tuple

Initializing a tuple with only one object is a little counter-intuitive. Try entering the following into your IDE:

my_tuple = ("the one and only",)  # notice the comma
print(type(my_tuple))  # prints <class 'tuple'>
my_tuple = ("the one and only")
print(type(my_tuple))  # prints <class 'str'>

Always remember to put a comma after the first element so that the compiler will understand the parentheses as tuple syntax, otherwise it will be mistaken as normal parentheses!

To include multiple objects in the initialization, Python allows any iterable to be inserted as a parameter:

# these all work and will run with no error
tup = tuple([2, 4, 6, 8])  # creates a tuple out of the list
tup = tuple('tuple')  # creates a tuple out of the string
tup = tuple({'a':'A', 'b':'B'})  # creates a tuple out of the dict
# note: it creates the tuple out of the dict's keys, not values
tup = tuple({2, 4, 6, 8})  # creates a tuple out of the set
tup = 2, 4, 6, 8  # you don't even need parentheses
# however, you need at least one element in the tuple to do this

Tuples are indexed the same way as lists, starting at 0, ending at length-1.

View on GitHub

Practice

Tuple Creator

Create an empty tuple and print the type of it. Create a tuple from any one element and print the type of it. Create a tuple from a given dictionary and print it. Note: The tuple created from a dictionary will only contain the keys of the dictionary.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.