LarsVegas
LarsVegas

Reputation: 6812

Difference accessing element(s) of tuple and list

Why is there this difference accessing the element(s) of t when making it a tuple?

>>> t = [('ID','int')]
>>> for r in t:
print r


('ID', 'int')


t = (('ID','int'))
>>> for r in t:
print r


ID
int

I'd expect this to be exactly the same as the first example! Whereas populating the tuple with more than one element the behavior changes.

>>> t = (('ID','int'),('DEF','str'))
>>> for r in t:
print r


('ID', 'int')
('DEF', 'str')
>>> t = [('ID','int'),('DEF','str')]
>>> for r in t:
print r


('ID', 'int')
('DEF', 'str')

Can somebody give a short explanation? I'm running python 2.7

Upvotes: 3

Views: 142

Answers (2)

Bill Lynch
Bill Lynch

Reputation: 81926

(('a', 'b')) is the same as ('a', 'b').

You actually want (('a', 'b'),)

This is documented here:

5.13. Expression lists

expression_list ::= expression ( "," expression )* [","]

An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.

The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: ().)

Remember, that without this restriction, should the expression (3) * (4) be the multiplication of two numbers, or two tuples? Most users would expect that to be the multiplication of numbers.

Upvotes: 14

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

t = [('ID','int')]

is a tuple in a list.

t = (('ID','int'))

is a tuple with brackets around it.

t = ('ID','int'),

is a tuple in a tuple.

The , makes the tuple! The brackets around a tuple are only needed to avoid ambiguity.

Upvotes: 4

Related Questions