6

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.

tacaswell
  • 84,579
  • 22
  • 210
  • 199
Spencer
  • 21,348
  • 34
  • 85
  • 121
  • 10
    This is the sort of question that makes google users hate SO. The title sounds so useful (and something one would google), but the question is so trivial and un-informative. – tacaswell Oct 02 '13 at 02:54
  • 5
    btw, this is the top hit for 'best way to iterate over tuples in python' – tacaswell Oct 02 '13 at 03:13

3 Answers3

37

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 1
    One really nice way to avoid using reserved names for variables is to use Pylint (http://www.pylint.org/) to check your code every time you save. I use Aptana with Pydev and Pylint to do this. – Carl Oct 02 '13 at 02:42
5
for i in my_tuples_name:
    print i

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

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
4

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.

Community
  • 1
  • 1
Attila O.
  • 15,659
  • 11
  • 54
  • 84