How To Apply A Function To Each Element Of A Tuple?

Rate this post

This article shows you how to apply a given function to each element of a tuple.

The best way to apply a function to each element of a tuple is the Python built-in `map(function, iterable)` function that takes a function and an iterable as arguments and applies the function to each iterable element. An alternate way is to use list comprehension

Note: All the solutions provided below have been verified in Python 3.9.5.

Problem Formulation

Imagine the following tuple of strings in Python.

```my_tuple = ('you',  'cannot',  'exercise',

How does one apply a function `string.upper()` to uppercase each string in the tuple?

`('YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET')`

I’ll start with the “naive approach” first and show you the more Pythonic solutions afterward. So, let’s get started!

Method 1: Simple For Loop

The above problem, like many others, has quite a simple solution in Python.

A simple solution uses a vanilla Python loop to iterate over each element of the original tuple. Apply the function to each element in the loop body and store the elements in a mutable container type such as a list. Finally, create a new tuple using the `tuple()` constructor and pass the new elements as arguments.

The result is a tuple of new elements — here stored in the variable `new_tuple` after applying the function `string.upper()` to each element of a Python tuple:

```my_tuple = ('you',  'cannot',  'exercise',

tmp = []
for element in my_tuple:
# Apply function to each element here:
tmp.append(element.upper())

# Create a new tuple here:
new_tuple = tuple(tmp)

print(new_tuple)
# ('YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET')
```

However, this is not the most Pythonic way to approach this problem.

Method 2: map()

Using the Python built-in `map()` function is the most efficient and elegant way to solve the problem. The `map(function, iterable)` function takes a function and an iterable as arguments and applies the given `function` to each element of the `iterable`.

For example, to apply the `string.upper()` function to each element of a Python tuple, use the `map(str.upper, my_tuple)` function to obtain a generator object. Now, convert the result to a tuple using the `tuple()` constructor and you’ve solved the problem!

This method is shown in the following code snippet:

```# 'my_tuple' is the original tuple whose string elements need to be
# fully uppercased. Note that 'my_tuple' is an object of the Python
# built-in Tuple class. Lists, Sets, Dicts and Tuples are considered
# iterables.
my_tuple = ('you',  'cannot',  'exercise',  'away',  'a',  'bad',  'diet')

# Use the upper() function of Python's built-in str class, to modify
# each element of the my_tuple iterable.
my_generic_iterable = map(str.upper, my_tuple)

# map() returns an iterable (or generator) object.
# It contains all the modified elements. Generators are temporary container
# objects. They can be iterated upon only once, to extract the elements
# within them. For example, use the 'tuple()' constructor to go thru each
# element of the 'my_generic_iterable' generator and generate a tuple.
new_tuple = tuple(my_generic_iterable)

print(new_tuple)
# Output:
# ['YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET']
```

If you need a quick explanation of the `map()` function, feel free to watch my training video here:

Personally, I’d use the following method—but this is only a matter of personal style.

Method 3: Generator Expression

You can use generator expressions to apply a function to each element of a tuple.

Here’s how to accomplish that:

```my_tuple = ('you',  'cannot',  'exercise',
new_tuple = tuple(str.upper(x) for x in my_tuple)

print(new_tuple)
# Output:
# ['YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET']
```

Generator expressions are similar to list comprehensions. You can learn more about list comprehensions in the following video—generator expressions work analogously but are more generally applicable:

Related Video

The following video shows how to apply a function to each element of a Python list. This is very similar to our problem, so it applies analogously to the solutions presented here:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!