How To Pass Tuple As Argument In Python

Tuples in Python are used as a collection of ordered, immutable elements. They are similar to lists but cannot be modified once they are created. In a Python program, you might want to pass a tuple as an argument to a function. This tutorial will explain how to do this step by step.

Step 1: Create a function to accept a tuple as an argument

First, you need to create a Python function that can accept a tuple as one of its arguments. You can pass a tuple to a function just like any other data type, without any special syntax. Here’s an example of a function that takes a tuple as an argument and prints out its elements:

In the above code, input_tuple is a function parameter that expects a tuple input.

Step 2: Create a tuple and call the function

Now, create a tuple and call the function with the tuple as an argument. Here’s an example:

In the above code, we defined a tuple named my_tuple and passed it as an argument to the print_tuple_elements function. The function will iterate the tuple and print each element.

Step 3: Working with multiple tuple arguments

You can also pass more than one tuple as arguments to a function, combining them into a single tuple. Here’s an example:

In the above code, we defined a function concatenate_tuples that accepts two tuples as arguments and returns a new tuple by combining them. We create two example tuples tuple_a and tuple_b and combined them using the function.

Output

(1, 2, 3, 4, 5, 6)

Step 4: Using the *args parameter for a variable number of tuple arguments

If you want the function to accept a variable number of tuple arguments, you can use the *args parameter. Here’s an example of a function that accepts multiple tuples and prints the length of each tuple:

In the above code, we defined a function print_lengths_of_tuples that accepts any number of tuples and prints the length of each tuple.

Output

2
3
4

Full code

To sum up, this tutorial showed you how to pass a tuple as an argument to a Python function. You can pass a single tuple, multiple tuples, or even a variable number of tuple arguments to a function using this method.