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.
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 −
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 (" ")
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.
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: >>>
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.
for i in my_tuples_name:
print i
You don't iterate over the keyword tuple, you iterate over your variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With