Python tuple object not callable

Python TypeError: ‘tuple’ object is not callable Solution

Tuples are enclosed within parentheses. This can be confusing because function calls also use parenthesis. If you use parentheses to access items from a tuple, or if you forget to separate tuples with a comma, you’ll encounter a “TypeError: ‘tuple’ object is not callable” error.

In this guide, we talk about what this error means and what causes it. We walk through two examples to help you understand how you can solve this error in your code.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: ‘tuple’ object is not callable

Tuples are defined as a list of values that are enclosed within parentheses:

coffees = ("Macchiato", "Americano", "Latte")

The parenthesis distinguishes a tuple from a list or a dictionary, which are enclosed within square brackets and curly braces, respectively.

Tuple objects are accessed in the same way as a list item. Indexing syntax lets you retrieve an individual item from a tuple. Items in a tuple cannot be accessed using parenthesis.

There are two potential causes for the “TypeError: ‘tuple’ object is not callable” error:

  • Defining a list of tuples without separating each tuple with a comma
  • Using the wrong indexing syntax

Let’s walk through each cause individually.

Cause #1: Missing Comma

The “TypeError: ‘tuple’ object is not callable” error is sometimes caused by one of the most innocent mistakes you can make: a missing comma.

Define a tuple that stores information about a list of coffees sold at a coffee shop:

coffees = [ ("Americano", 72, 1.90), ("Macchiato", 93, 2.10) ("Latte", 127, 2.30) ]

The first value in each tuple is the name of a coffee. The second value is how many were sold yesterday at the cafe. The third value is the price of the coffee.

Now, let’s print “coffees” to the console so we can see its values in our Python shell:

Traceback (most recent call last): File "main.py", line 3, in ("Macchiato", 93, 2.10) TypeError: 'tuple' object is not callable

As we expected, an error is returned. This is because we have forgotten to separate all the tuples in our list of coffees with a comma.

Читайте также:  Unicodedecodeerror python utf 8

When Python sees a set of parenthesis that follows a value, it treats the value as a function to call. In this case, our program sees:

("Macchiato", 93, 2.10)("Latte", 127, 2.30)

Our program tries to call (“Macchiato”, 93, 2.10) as a function. This is not possible and so our code returns an error.

To solve this problem, we need to make sure that all the values in our list of tuples are separated using commas:

coffees = [ ("Americano", 72, 1.90), ("Macchiato", 93, 2.10), ("Latte", 127, 2.30) ] print(coffees)

We’ve added a comma after the tuple that stores information on the Macchiato coffee. Let’s try to run our code again:

[('Americano', 72, 1.9), ('Macchiato', 93, 2.1), ('Latte', 127, 2.3)]

Our code successfully prints out our list of tuples.

Cause #2: Incorrect Indexing Syntax

Here, we write a program that stores information on coffees sold at a coffee shop. Our program will then print out each piece of information about each type of coffee beverage.

Start by defining a list of coffees which are stored in tuples:

coffees = [ ("Americano", 72, 1.90), ("Macchiato", 93, 2.10), ("Latte", 127, 2.30) ]

Next, write a for loop that displays this information on the console:

for c in coffees: print("Coffee Name: " + str(c(0))) print("Sold Yesterday: " + str(c(1))) print("Price: $" + str(c(2))))

This for loop should print out each value from all the tuples in the “coffees” list. We convert each value to a string so that we can concatenate them to the labels in our print() statements.

Run our code and see what happens:

Traceback (most recent call last): File "main.py", line 8, in print("Coffee Name: " + c(0)) TypeError: 'tuple' object is not callable

Our code returns an error.

This error is caused because we are trying to access each item from our tuple using curly brackets. While tuples are defined using curly brackets, their contents are made accessible using traditional indexing syntax.

To solve this problem, we have to use square brackets to retrieve values from our tuples:

for c in coffees: print("Coffee Name: " + str(c[0])) print("Sold Yesterday: " + str(c[1])) print("Price: $" + str(c[2]))

Let’s execute our code with this new syntax:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Coffee Name: Americano Sold Yesterday: 72 Price: $1.9 Coffee Name: Macchiato Sold Yesterday: 93 Price: $2.1 Coffee Name: Latte Sold Yesterday: 127 Price: $2.3

Our code successfully prints out information about each coffee.

Читайте также:  How to check if string is in string php

Conclusion

The “TypeError: ‘tuple’ object is not callable” error is raised when you try to call a tuple as a function. This can happen if you use the wrong syntax to access an item from a tuple or if you forget to separate two tuples with a comma.

Make sure when you access items from a tuple you use square brackets. Also ensure that all tuples in your code that appear in a list are separated with a comma.

Now you’re ready to solve this error like a Python pro!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

How to Solve Python TypeError: ‘tuple’ object is not callable

TypeError occurs in Python when you perform an illegal operation for a specific data type.

What Does Callable Mean?

Calling a function means the Python interpreter executes the code inside the function. In Python, we can only call functions. We can call functions by specifying the name of the function we want to use followed by a set of parentheses, for example, function_name(). Let’s look at an example of a working function that returns a string.

# Declare function def simple_function(): print("Hello World!") # Call function simple_function()

We declare a function called simple_function in the code , which prints a string. We can then call the function, and the Python interpreter executes the code inside simple_function() .

We use tuples to store multiple items in a single variable. Tuples do not respond to a function call because they are not functions. If you try to call a tuple, the Python interpreter will raise the error TypeError: ‘tuple’ object is not callable. Let’s look at examples of raising the error and how to solve it:

Example #1: Not Using a Comma to Separate Tuples

Let’s look at an example where we define a list of tuples. Each tuple contains three strings. We will attempt to print the contents of each tuple as a string using the join() method.

# Define list of tuples lst = [("spinach", "broccolli", "asparagus"), ("apple", "pear", "strawberry") ("rice", "maize", "corn") ] # Print types of food print(f"Vegetables: ") print(f"Fruits: ") print(f"Grains: ")

Let’s run the code to see what happens:

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [1], in () 1 # Define list of tuples 3 lst = [("spinach", "broccolli", "asparagus"), 4 ----> 5 ("apple", "pear", "strawberry") 6 7 ("rice", "maize", "corn") 8 ] 10 # Print types of food 12 print(f"Vegetables: ") TypeError: 'tuple' object is not callable

We get the TypeError because we do not have a comma separating the second and third tuple item in the list. The Python Interpreter sees this as an attempt to call the second tuple with the contents of the third tuple as arguments.

Читайте также:  Css прокрутка строк таблицы

Solution

To solve this error, we need to place a comma after the second tuple. Let’s look at the revised code:

# Define list of tuples lst = [("spinach", "broccolli", "asparagus"), ("apple", "pear", "strawberry"), ("rice", "maize", "corn") ] # Print types of food print(f"Vegetables: ") print(f"Fruits: ") print(f"Grains: ")

Let’s run the code to get the correct output:

Vegetables: spinach broccolli asparagus Fruits: apple pear strawberry Grains: rice maize corn

Example #2: Incorrectly Indexing a Tuple

Let’s look at an example where we have a tuple containing the names of three vegetables. We want to print each name by indexing the tuple.

# Define tuple veg_tuple = ("spinach", "broccolli", "asparagus") print(f"First vegetable in tuple: ") print(f"Second vegetable in tuple: ") print(f"Third vegetable in tuple: ")

Let’s run the code to see what happens:

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 veg_tuple = ("spinach", "broccolli", "asparagus") 2 ----≻ 3 print(f"First vegetable in tuple: ") 4 print(f"Second vegetable in tuple: ") 5 print(f"Third vegetable in tuple: ") TypeError: 'tuple' object is not callable

The error occurs because we are using parentheses to index the tuple instead of the indexing operator []. The Python interpreter sees this as calling the tuple passing an integer argument.

Solution

To solve this error, we need to replace the parenthesis with square brackets. Let’s look at the revised code:

# Define tuple veg_tuple = ("spinach", "broccolli", "asparagus") print(f"First vegetable in tuple: ") print(f"Second vegetable in tuple: ") print(f"Third vegetable in tuple: ")

Let’s run the code to get the correct output:

First vegetable in tuple: spinach Second vegetable in tuple: broccolli Third vegetable in tuple: asparagus

Summary

Congratulations on reading to the end of this tutorial. To summarize, TypeError’ tuple’ object is not callable occurs when you try to call a tuple as if it were a function. To solve this error, ensure when you are defining multiple tuples in a container like a list that you use commas to separate them. Also, if you want to index a tuple, use the indexing operator [] , and not parentheses.

For further reading on not callable TypeErrors, go to the article: How to Solve Python TypeError: ‘float’ object is not callable.

To learn more about Python, specifically for data science and machine learning, go to the online courses page on Python.

Have fun and happy researching!

Share this:

Источник

Оцените статью