Tue Jun 14 2022·3 min read
Photo by Andre Furtado
len() function to get the length of a tuple, e.g.
result = len(my_tuple). The
len() function returns the length (the number of
items) of an object and can be passed a sequence (a tuple, string, list, range
or bytes) or a collection (a dictionary, set, or frozen set).
# 👇 get length of a tuple my_tuple = ('a', 'b', 'c') result_1 = len(my_tuple) print(result_1) # 👉️ 3 # 👇️ get length of tuple inside of a list my_list = [('a', 'b'), ('c', 'd')] result_2 = len(my_list) print(result_2) # 👉️ 2
The len() function returns the length (the number of items) of an object.
The first example shows how to get the number of items in the tuple.
Indices are zero-based, so the index of the first item in the tuple is
the index of the last item is
len(my_tuple) - 1.
The last item in the tuple can also be accessed using
my_tuple = ('a', 'b', 'c') print(len(my_tuple)) # 👉️ 3 print(my_tuple) # 👉️ 'a' print(my_tuple[-1]) # 👉️ 'c' print(my_tuple[len(my_tuple) - 1]) # 👉️ 'c'
If you need to count the items in a tuple that satisfy a condition, use a list
comprehension to get a subset of items that match the condition and pass the
results to the
my_tuple = (1, 2, 3, 4, 5) result = len([x for x in my_tuple if x > 3]) print(result) # 👉️ 2
The example gets the count of tuple items that are greater than
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
Tuples are constructed in multiple ways:
()creates an empty tuple
You can also use the
len() function to check if a tuple is empty.
my_tuple = () if len(my_tuple) == 0: # 👇️ this runs print('tuple is empty') else: print('tuple is NOT empty')
If a tuple has a length of
0, then it's empty.
You might also see examples online that check whether the tuple is truthy (to check if it contains at least 1 item), which is more implicit.
my_tuple = () if my_tuple: print('tuple is NOT empty') else: # 👇️ this runs print('tuple is empty')
All values that are not truthy are considered falsy. The falsy values in Python are:
0(zero) of any numeric type
Notice that an empty tuple is a falsy value, so if the tuple is empty, the
else block is ran.
If you need to check if the tuple is empty using this approach, you would negate
the condition with
my_tuple = () if not my_tuple: # 👇️ this runs print('tuple is empty') else: print('tuple is NOT empty')