1

I've noticed a weird behavior when iterating over a tuple containing only 1 string:

foo = ("hello")
for entry in foo:
    print(entry)

outputs:

h
e
l
l
o

But I expect here to iterate only once, and output "hello" in a row.

If my tupple contains 2 entries, that's what happening:

foo = ("hello", "world!")
for entry in foo:
    print(entry)

outputs:

hello
world!

Is it a bug in CPython's implementation? Even weirder, this doesn't occur if I use a list instead of a tuple:

foo = ["hello"]
for entry in foo:
    print(entry)

outputs:

hello

2 Answers2

8

("hello") is not a tuple - it's a string, surrounded with parenthesis, which are meaningless in this context. If you want a single-element tuple, you need a comma after the value:

foo = ("hello",) 
# Here--------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You have a string not a tuple:

>>> type(('hello'))
<class 'str'>
>>> type(('hello',))
<class 'tuple'>
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139