Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error iterating over tuple in python

I am new to Python and am unsure of the best way to iterate over a tuple.

The syntax

for i in tuple
    print i

causes an error. Any help will be much appreciated! I am a ruby programmer new to python.

like image 818
Spencer Avatar asked Aug 31 '11 22:08

Spencer


People also ask

How to iterate through a tuple in Python?

There are different ways to iterate through a tuple object. The for statement in Python has a variant which traverses a tuple till it is exhausted. It is equivalent to foreach statement in Java. Its syntax is − Following script will print all items in the list The output generated is −

How to iterate over tuples in a dictionary with for loop?

Tuple mapped with the key 1 => ('Apple', 'Boy', 'Cat') Tuple mapped with the key 2 => Geeks For Geeks Tuple mapped with the key 3 => I Am Learning Python we can use dictionary.values () to iterate over the tuples in a dictionary with for loop for i in dictionary_name.values (): for j in i: print (j) print (" ")

Why can’t I call a tuple in Python?

This would be valid syntax in Python versions before 3.8, but the code would raise a TypeError because a tuple is not callable: This TypeError means that you can’t call a tuple like a function, which is what the Python interpreter thinks you’re doing.

Why do I keep getting syntax errors in Python?

You’ll see this warning in situations where the syntax is valid but still looks suspicious. An example of this would be if you were missing a comma between two tuples in a list. This would be valid syntax in Python versions before 3.8, but the code would raise a TypeError because a tuple is not callable: >>>


3 Answers

That is an error because the syntax is invalid, add a colon:

for i in tup:
    print i

Also, you should not use tuple as the name for a variable, as it is the name of a built-in function.

like image 196
Andrew Clark Avatar answered Oct 07 '22 21:10

Andrew Clark


for i in my_tuples_name:
    print i

You don't iterate over the keyword tuple, you iterate over your variable.

like image 31
Jakob Bowyer Avatar answered Oct 07 '22 22:10

Jakob Bowyer


You seem to have forgotten a colon.

for i in my_tuple:
    print i

Also look at this related answer.

EDIT: And I didn't notice you were iterating over the keyword tuple, as noted. by F.J. and Jakob Bowyer.

like image 35
Attila O. Avatar answered Oct 07 '22 23:10

Attila O.