Tuple object is not callable python ошибка

import math
 print ("Для начала , найдём первую ёмкость ")
 print ("Введи данные первой ёмкости ")
  h = float(input('Введи высоту цилиндра , в первой ёмкости '))
  dm = float(input('Введи диаметр цилиндра , в первой ёмкости '))
  R = int(input('Радиус конца с сегментами '))
  V1 = int(input('Объём заполняемого '))
  konc = int(input('Концетрация '))
  potr = float(input('Потребность в производстве '))
  plt = float(input('Плотность вещества '))
  tsm = int(input('Часов в смене '))
  pi = float(input('Чему равно PI '))
  print ('Рассчитаем массу ёмкости и кол-во смен ')
  print ('Решение')
  rcc = dm/2
  rc = float(rcc)
 print(rc ,'м - радиус цилиндра')
  D = float(R*2)
 print(D ,'м - диаметр сегментов')
  H11 =((D-dm)**2 - (D-dm)/2)
  H1 = float(H11)
  H = math.sqrt(H1)
 print = (H ,' - Высота усечённого конуса')
  Vcil = pi*(rc**2)*h
 print (Vcil,' - объём цилиндрической части')
  Vseg = pi * H * (R**2 + R*rc + rc**2)
  print (Vseg , " - объём сегментивной части")
  Vem = Vcil + 2*Vseg
 print (Vem, " - Объём емкости")
  Vzap = Vem * (V1/100)
 print (Vzap,' - объём запасов')
 print ('Теперь , найдём объём латекса')
  Vlat = Vzap * (konc/100)
 print (Vlat,'m^3 - обём латекса')
 print ('Теперь , найдём массу латекса')
  m1 = plt * Vlat
 print (m1,'кг - масса латекса')
  Qsm = potr * tsm
 print (Qsm,' - Расход латекста за смену')
  Nsm = Vlat / Qsm
 print (Nsm, '- Колличество смен')

При компиляции пишет , что на 25 строке произошёл косяк : tuple object is not callable , перед этим должно вывести H

If you try to call a tuple object, you will raise the error “TypeError: ‘tuple’ object is not callable”.

We use parentheses to define tuples, but if you define multiple tuples without separating them with commas, Python will interpret this as attempting to call a tuple.

To solve this error, ensure you separate tuples with commas and that you index tuples using the indexing operator [] not parentheses ().

This tutorial will go through how to solve this error with the help of code examples.


Table of contents

  • TypeError: ‘tuple’ object is not callable
    • What is a TypeError?
    • What Does Callable Mean?
  • Example #1: Not Using a Comma to Separate Tuples
    • Solution
  • Example #2: Incorrectly Indexing a Tuple
    • Solution
  • Summary

TypeError: ‘tuple’ object is not callable

What is a TypeError?

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()
Hello World!

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: {' '.join(lst[0])}")

print(f"Fruits: {' '.join(lst[1])}")

print(f"Grains: {' '.join(lst[2])}")

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [1], in <cell line: 3>()
      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: {' '.join(lst[0])}")

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.

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: {' '.join(lst[0])}")

print(f"Fruits: {' '.join(lst[1])}")

print(f"Grains: {' '.join(lst[2])}")

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: {veg_tuple(0)}")

print(f"Second vegetable in tuple: {veg_tuple(1)}")

print(f"Third vegetable in tuple: {veg_tuple(2)}")

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: {veg_tuple(0)}")
      4 print(f"Second vegetable in tuple: {veg_tuple(1)}")
      5 print(f"Third vegetable in tuple: {veg_tuple(2)}")

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: {veg_tuple[0]}")

print(f"Second vegetable in tuple: {veg_tuple[1]}")

print(f"Third vegetable in tuple: {veg_tuple[2]}")

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!

Introduction

In this article, we are exploring something new. From the title itself, you must be curious to know about the terms such as TypeError, tuple in python. So putting an end to your curiosity, let’s start with today’s tutorial on how to solve TypeError: ‘Tuple’ Object is not Callable in Python.

A tuple is one of the four in-built data structures provided by python. It is a collection of elements that are ordered and are enclosed within round brackets (). A tuple is immutable, which means that it cannot be altered or modified. Creating a tuple is simple, i.e., putting different comma-separated objects. For example: – T1 = (‘Chanda’, 11, ‘Kimmi’, 20).

Causes of TypeError: 'Tuple' Object is not Callable in Python

Tuple in python

What is Exception in python?

Sometimes we often notice that even though the statement is syntactically correct in the code, it lands up with an error when we try to execute them. These errors are known as exceptions. One of these exceptions is the TypeError exception. Generally, other exceptions, including the TypeError exception, are not handled by program. So let’s do some code to understand exceptions.

OUTPUT: - Traceback (most recent call last):  
                       File "<stdin>", line 1, in <module>
                         ZeroDivisionError: division by zero

The last line of the error message indicates what kind of exception has occurred. The different types of exceptions are:

  • ZeroDivisionError
  • NameError
  • TypeError

What is TypeError Exception in Python?

TypeError exception occurs when an operation is performed to an object of inappropriate data type. For example, performing the addition operation on a string and an integer value will raise the TypeError exception. Let’s do some code to have a clear understanding.

str = 'Favorite'
num = 5
print(str + num + str)
OUTPUT: - TypeError: Can't convert 'int' object to str implicitly  

In the above example, the variable ‘str’ is a string, and the variable ‘num’ is an integer. The addition operator cannot be used between these two types, and hence TypeError is raised.

Let us understand different type of TypeError exception which is Incorrect type of list index.

list1 = ["physics", "chemistry", "mathematics", "english"]
index = "1"
print(list1[index])
OUTPUT: - TypeError: list indices must be integers or slices, not str

In the above-written Python code, the list index must always be an integer value. Since the index value used is a string, it generates a TypeError exception.

Till now, you must have understood the TypeError exception. Now let’s dive deeper into the concept of TypeError exception occurring in a tuple or due to a tuple.

TypeError: ‘tuple’ object is not callable

You must be wondering why this type of TypeError occurs. This is because tuples are enclosed with parenthesis creates confusion as parenthesis is also used for a function call wherein we pass parameters. Therefore, if you use parenthesis to access the elements from a tuple or forget to separate tuples with a comma, you will develop a “TypeError: ‘tuple’ object not callable” error. There are two causes for the “TypeError: ‘tuple’ object is not callable” error, and they are the following:

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

Let’s us discuss in detail.

Cause 1. Missing Comma

Sometimes the “TypeError: ‘tuple’ object is not callable” error is caused because of a missing comma. Let’s start to code to understand this.

marks = [
	("Kimmi", 72),
	("chanda", 93)
	("Nupur", 27)
]
print(marks)
OUTPUT:-

Traceback (most recent call last):                                                                                                        
  File "main.py", line 4, in <module>                                                                                                     
    ("Nupur", 27)                                                                                                                       
TypeError: 'tuple' object is not callable 

As expected, an error was thrown. This is because we have forgotten to separate all the tuples in our list with a comma. When python sees a set of parenthesis that follows a value, it treats the value as a function to call.

Cause 2: Incorrect syntax of an index

Let’s us first code to understand this cause.

marks = [
	("Kimmi", 72),
	("chanda", 93),
	("Nupur", 27)
]
for i in marks:
    print("Names: " +str(i(0)))
    print("Marks: " +str(i(1)))
OUTPUT: - Traceback (most recent call last):                                                                                                            
  File "main.py", line 7, in <module>                                                                                                        
    print("Names: " +str(i(0)))                                                                                                               
TypeError: 'tuple' object is not callable 

The above loop should print each value from all the tuples in the “marks” list. We converted each value to a string so that it is possible to concatenate them to the labels in our print statements, but our code throws an error.

The reason behind this is that we are trying to access each item from our tuple using round brackets. While tuples are defined using round brackets, i.e., (), their contents are made accessible using traditional indexing syntax. Still, the tuples are defined using round brackets. Therefore, their contents are made accessible using traditional indexing syntax.

You must be thinking now about what we should do to make our code executable. Well, it’s simple. But, first, we have to use square brackets [ ] to retrieve values from our tuples. So, Let’s look at our code.

marks = [
	("Kimmi", 72),
	("chanda", 93),
	("Nupur", 27)
]
for i in marks:
    print("Names: " +str(i[0]))
    print("Marks: " +str(i[1]))
OUTPUT: - 

Names: chanda                                                                                                                                 
Marks: 93                                                                                                                                     
Names: Nupur                                                                                                                                  
Marks: 27   

Our code successfully executes the information about each student.

Also Read | NumPy.ndarray object is Not Callable: Error and Resolution

What objects are not callable in Python?

Previously, we discussed the Tuple object is not callable in python; other than that, we also have another object which is not callable, and that is the list.

1. typeerror: ‘list’ object is not callable 

When you try to access items in a list using round brackets (), Python returns an error called the typeerror. This is because Python thinks that you are trying to call a function.

The solution to this problem is to use square brackets [ ] to access the items in a list. We know that round brackets are usually used to call a function in python.

2. typeerror: ‘module’ object is not callable 

While using the functions, we also use modules to import and then use them. This might create confusion. because, in some cases, the module name and function name may be the same. For example, the getopt module provides the getopt() function, which may create confusion. Callable means that a given python object can call a function, but in this error, we warned that a given module could not be called like a function.

The solution to this problem is that we will use from and import statements. from is used to specify the module name, and import is used to point to a function name.

3. typeerror: ‘int’ object is not callable

Round brackets in Python have a special meaning. They are used to call a function. If you specify a pair of round brackets after an integer without an operator between them, the Python interpreter will think that you’re trying to call a function, and this will return a “TypeError: ‘int’ object is not callable” error.

4. typeerror: ‘str’ object is not callable

Mistakes are often committed, and it is a human error. Therefore, our error message is a TypeError. This tells us that we are trying to execute an operation on a value whose data type does not support that specific operation. From the above statement, I meant that when you try to call a string like you would a function, an error will be returned. This is because strings are not functions. To call a function, you add round brackets() to the end of a function name.

This error occurs when you assign a variable called “str” and then try to use the function. Python interprets “str” as a string, and you cannot use the str() function in your program.

Also, Read | How to Solve TypeError: ‘int’ object is not Subscriptable

Conclusion

The “TypeError: ‘tuple’ object is not callable” error occurs 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.

Ensure that when you access items from a tuple, you use square brackets and ensure that all tuples in your code should be separated with a comma.

Now you’re ready to fix this error in your code like a professional Python developer!. Till then, keep reading articles.

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.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

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:

Our code returns:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	("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.

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 <module>
	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.

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!

Posted on Mar 22, 2023


When working with Python, you might encounter the following error:

TypeError: 'tuple' object is not callable

This error occurs when you try to call a tuple object as if it was an object. There are two scenarios where this error might occur:

  1. You try to access a specific index using parentheses
  2. You create a list of tuples but forgot to use a comma to separate each tuple
  3. You mistakenly create a variable named tuple

Because Python uses parentheses to initialize a tuple and call a function, many programmers unintentionally tripped on this error.

This tutorial shows how to fix the error in each scenario.

1. You used parentheses to access a tuple item at a specific index

Suppose you initialize a Python tuple as follows:

my_tuple = ('a', 'b', 'c')

Next, you try to access the second item in the tuple with the following code:

The output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    my_tuple(1)
TypeError: 'tuple' object is not callable

This error occurs because you used parentheses () to access the tuple at a specific index.

To access an item inside a tuple, you need to use the square brackets [] notation.

Here’s the right way to access a tuple item:

my_tuple = ('a', 'b', 'c')

x = my_tuple[1]
print(x)  # b

Notice that this time we didn’t receive the error.

2. You created a list of tuples but forgot to use a comma to separate each tuple

This error also occurs when you create a list of tuples, but forgot to separate each tuple using a comma.

Here’s an example code that causes the error:

number_list = [
  (1, 2, 3)
  (4, 5, 6)
]

The number_list contains two tuples, but there’s no comma separating them.

As a result, Python thinks you’re putting a function call notation next to a tuple like this:

my_tuple = (1, 2, 3)

number_list = [
  my_tuple(4, 5, 6)
]

To resolve this error, you need to separate each tuple using a comma as follows:

number_list = [
  (1, 2, 3),
  (4, 5, 6)
]

By adding a comma between two tuples, the error should be resolved.

3. You created a variable named tuple in your source code

The built-in function named tuple() is used to convert an object of another type into a tuple object.

For example, here’s how to convert a list into a tuple:

my_list = [1, 2, 3]

my_tuple = tuple(my_list)
print(my_tuple)  # (1, 2, 3)

If you mistakenly create a variable named tuple, then the tuple() function would be overwritten.

When you call the tuple() function, the error would occur as follows:

tuple = (1, 2, 3)

another_tuple = tuple(['a', 'b'])

Output:

Traceback (most recent call last):
  File "/main.py", line 3, in <module>
    another_tuple = tuple(['a', 'b'])
TypeError: 'tuple' object is not callable

Because you created a variable named tuple, the tuple() function gets replaced with that variable, causing you to call a tuple object instead of a tuple function.

To avoid this error, you need to declare the variable using another name:

my_tuple = (1, 2, 3)  # ✅

another_tuple = tuple(['a', 'b'])

This way, the keyword tuple would still point to the tuple function, and the error won’t be raised.

Conclusion

The TypeError: 'tuple' object is not callable occurs when you mistakenly call a tuple object as if it’s a function.

To resolve this error make sure that:

  1. You don’t access a tuple item using parentheses
  2. When creating multiple tuples, you separate each tuple with a comma
  3. You don’t use the tuple keyword as a variable name

By following the steps above, you can avoid the error appearing in your source code.

I hope this tutorial is helpful. See you in other tutorials! 👋

Понравилась статья? Поделить с друзьями:
  • Tunnelbear ошибка установки
  • Tunnelbear ошибка подключения к серверу
  • Tunnelbear 1009 ошибка
  • Tucson ошибка 0133
  • Tube plugged ошибка кофемашина что делать