[Tutor] multiple objects with one assignment?

Steven D'Aprano steve at pearwood.info
Fri Jan 2 16:17:02 CET 2015


On Fri, Jan 02, 2015 at 06:51:16AM -0500, Brandon Dorsey wrote:
> On Fri, Jan 2, 2015 at 6:34 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 
> > The thing to remember is that *commas*, not parentheses, are used for
> > making tuples. The round brackets are just for grouping.
> >
> 
> That's what I was confused about.  I didn't realize commas defined tuples,
> not parentheses.  Is this the case
> for list and dictionaires as well?

No.

x = 1, 2
y = 1, 2

cannot make a tuple for x and a list for y. How would the compiler know 
which you wanted?

The syntax for lists:

    [a, b, c, ... ]

requires the square brackets. You must have a comma between items, and 
optionally after the last item. That makes it easy to add new items to 
large lists without worrying about keeping the last item special. Here's 
an example from some code of mine:

PRIMES = [2,   3,   5,   7,   11,  13,  17,  19,  23,  29,
          31,  37,  41,  43,  47,  53,  59,  61,  67,  71,
          73,  79,  83,  89,  97,  101, 103, 107, 109, 113,
          ]

Now I can add or remove lines without bothering to remove the comma from 
the very last line. 

If there are no items, you can't use a comma:

x = [,]

is a syntax error.

Likewise for dicts, and in Python 3, sets:

d = {1:'a', 2:'b'}
s = {1, 2, 3}  # set syntax is Python 3 only


It is the curly brackets { } that tell Python you're creating a dict or 
set, not the commas. The commas separate items, that is all.


-- 
Steven


More information about the Tutor mailing list