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

Cover image for How to fix "‘tuple’ object is not callable" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “TypeError: ‘tuple’ object is not callable” error occurs when you try to call a tuple as if it was a function!

Here’s what the error looks like:

Traceback (most recent call last):
  File "/dwd/sandbox/test.py", line 4, in 
    print(range_config('title'))
          ^^^^^^^^^^^^^^^^^^^^^
TypeError: 'tuple' object is not callable

Enter fullscreen mode

Exit fullscreen mode

Calling a tuple object as if it’s a callable isn’t what you’d do on purpose, though. It usually happens due to a wrong syntax or accidentally overriding a function’s global name with a tuple object!

Let’s explore the common causes and their solutions.

How to fix TypeError: ‘tuple’ object is not callable?

This TypeError happens under various scenarios:

  1. Accessing a tuple item by () rather than []
  2. A missing comma before a nested tuple
  3. Defining a tuple with a global name that’s also the name of a function
  4. Calling a method that’s also the name of a property
  5. Calling a method decorated with @property

Accessing a tuple item by parenthesis rather than square brackets: The most common cause of this TypeError is accessing a tuple item by () instead of [].

Based on Python semantics, any identifier followed by a () is a function call. In this case, since () follows a tuple, it’s like you’re trying to call the tuple like it’s callable.

As a result, you’ll get the «TypeError: ‘tuple’ object is not callable» error.

range_config = (1, 10)

 # ⛔ Raises: TypeError: ‘tuple’ object is not callable
print(range_config(0))

Enter fullscreen mode

Exit fullscreen mode

This is how you’re supposed to access a tuple value:

range_config = (1, 10)

# You should access a value in a tuple by []
print(range_config[0])

Enter fullscreen mode

Exit fullscreen mode

A missing comma before a nested tuple: Unlike other sequence data types, you can create tuples in a variety of ways. Understanding tuple syntax helps you avoid confusion while debugging this issue.

As you already know, a tuple consists of several values separated by commas (with or without surrounding parentheses).

When creating tuples, remember:

  1. You can create tuples without parenthesis
  2. () creates an empty tuple
  3. Tuples with one item need a comma at the end: (12,)

Here are some examples in a Python Shell:

>>> 3984, 'someValue', True
(3984, 'someValue', True)
>>>
>>> ()
()
>>>
>>> ((),)
((),)
>>>
>>> (3984,)
(3984,)
>>>
>>> tuple([1, 2, 3])
(1, 2, 3)
>>>
>>> 3984, 'someValue', ('nestTupleValue',), ('nestedTupleValue', 2345)
(3984, 'someValue', ('nestTupleValue',), ('nestedTupleValue', 2345))

Enter fullscreen mode

Exit fullscreen mode

But how a missing comma can lead to this TypeError? You may ask.

Let’s see an example:

>>> 3984, 'someValue', ('nestTupleValue',) ('nestedTupleValue', 2345)

<stdin>:1: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Enter fullscreen mode

Exit fullscreen mode

In the above example, the last two items in our tuple are also tuples (nested tuple). However, a comma is missing between them. As a result, Python’s interpreter doesn’t include the last item in the tuple. Consequently, it thinks we’re trying to call our tuple with two arguments, meaning 'nestedTupleValue' and 2345.

Since a tuple isn’t a callable, you get the TypeError.

That said, whenever you get this error at a specific line, check if you’ve missed a comma before a nested tuple.

Defining a tuple with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as str, int, float, dict, tuple, list, etc.

All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, the global name tuple refers to the tuple class.

That said, overriding a function’s global name (accidentally or on purpose) with any value (e.g., a tuple) is technically possible.

In the following example, we’ve declared a variable named range containing some config data in a tuple. In its following line, we use the range() function in a for loop:

# Creating tuple named range
range = (1, 10)
# ⚠️ The above line overrides the original value of range (the 'range' class)

for i in range(5, 15, 2):
    print(i)

Enter fullscreen mode

Exit fullscreen mode

If you run the above code, Python will complain with a «TypeError: ‘tuple’ object is not callable» error because we’ve already assigned the range global variable to our tuple.

We have two ways to fix the issue:

  1. Rename the variable range
  2. Explicitly access the range() function from the builtins module (__bultins__.range)

The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open():

# Custom open() function using the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...

Enter fullscreen mode

Exit fullscreen mode

In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.

So the above example could be fixed like this:

This issue is common with function names you’re more likely to use as variable names. Functions such as vars, locals, list, tuple, all, or even user-defined functions.

⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!

Overriding functions (and calling them later on) is one of the most common causes of the «TypeError: ‘tuple’ object is not callable» error. It’s similar to calling integer numbers.

Now, let’s get to the less common mistakes that lead to this error.

Calling a method that’s also the name of a property: When you define a property in a class constructor, it’ll shadow any other attribute of the same name.

class Book:
    def __init__(self, title, authors):
        self.title = title
        self.authors = authors

    def authors(self):
        return self.authors

authors = ('Andy Hunt', 'Dave Thomas')
book = Book('Head First Python', authors)

print(book.authors())
# 👆 ⛔ Raises TypeError: 'dict' object is not callable

Enter fullscreen mode

Exit fullscreen mode

In the above example, we have a property named authors — a tuple to keep the authors’ names. Further down, we defined a method, also named authors.

However the property authors shadows the method. As a result, any reference to authors returns the property — a tuple object — not the method. And if you try to call this tuple object, you should expect the «TypeError: ‘tuple’ object is not callable» error.

The name get_authors sounds like a safer and more readable alternative:

class Book:
    def __init__(self, title, authors):
        self.title = title
        self.authors = authors

    def get_authors(self):
        return self.authors

authors = ('Andy Hunt', 'Dave Thomas')
book = Book('Head First Python', authors)

print(book.get_authors())
# Output: ('Andy Hunt', 'Dave Thomas')

Enter fullscreen mode

Exit fullscreen mode

Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name. You need to access a getter method without parenthesis, otherwise you’ll get a TypeError.

class Book:
    def __init__(self, title, authors):
        self._title = title
        self._authors = authors

    @property
    def authors(self):
        return self._authors

authors = ('Andy Hunt', 'Dave Thomas')
book = Book('Head First Python', authors)

print(book.authors())
# 👆 ⛔ Raises TypeError: 'tuple' object is not callable

Enter fullscreen mode

Exit fullscreen mode

To fix it, you need to access the getter method without the parentheses:

class Book:
    def __init__(self, title, authors):
        self._title = title
        self._authors = authors

    @property
    def authors(self):
        return self._authors

authors = ('Andy Hunt', 'Dave Thomas')
book = Book('Head First Python', authors)

print(book.authors)
# Output: ('Andy Hunt', 'Dave Thomas')

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Alright, I think it does it! I hope this quick guide helped you fix your problem.

Thanks for reading.

❤️ You might like:

  • TypeError: ‘dict’ object is not callable in Python
  • TypeError: ‘list’ object is not callable in Python
  • TypeError: ‘str’ object is not callable in Python
  • TypeError: ‘float’ object is not callable» in Python
  • TypeError: ‘int’ object is not callable in Python

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.

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!

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!

Понравилась статья? Поделить с друзьями:
  • Tunngle ошибка install incomplete please download and run
  • Tunnelbear ошибка подключения к серверу
  • Tube plugged ошибка кофемашина что делать
  • Tube plugged ошибка кофемашина polaris
  • Tst already a reissue ошибка амадеус