2007/10/13

Python and comma

The problem - there was a tuple:
t = ("abc", "def")
Somwhere inside the program was an instruction:
something = t[0]
and then
something
returned "abc".



Some time later it turned out that "def" was not necessary
in t so was modified:
t = ("abc")
and sowhere inside the program instruction
something = t[0]
made that something returned "a".

It was Bad.

Why that happened?

Beacuse t was not a tuple anymore, it became a string. Instruction t[0] returns first item in iterable so it returned "a" for us.

What was ommited?

A coma.

After the change it was (bad):
t = ("abc")
instead (good):
t = ("abc",)

The coma creates a tuple. In our case consisting of one item, but still the tuple.

2 comments:

Paddy3118 said...

Yep,
Someone stated "It's the comma that makes the tuple. Not the brackets". And I found that easy to remember.

- Paddy.

places-to-visit.info said...

I've come to the idea of this post after second hunting for the cause of the error in a week. It's mainly for myself as an aid for my memory, but maybe someone will benefit from it. Anyway, sentence cited by Paddy3118 is definitely worth to be remembered.