82

Is there a way in Python to do like this:

a, b, = 1, 3, 4, 5

and then:

>>> a
1
>>> b
3

The above code doesn't work as it will throw

ValueError: too many values to unpack

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

5 Answers5

149

Just to add to Nolen's answer, in Python 3, you can also unpack the rest, like this:

>>> a, b, *rest = 1, 2, 3, 4, 5, 6, 7
>>> a
1
>>> rest
[3, 4, 5, 6, 7]

Unfortunately, this does not work in Python 2 though.

Gustav Larsson
  • 8,199
  • 3
  • 31
  • 51
69

There is no way to do it with the literals that you've shown. But you can slice to get the effect you want:

a, b = [1, 3, 4, 5, 6][:2]

To get the first two values of a list:

a, b = my_list[:2]
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 1
    +1 even though the OP said he already knew this but it seems to be edited out of the question. – jamylak Jul 07 '12 at 00:23
36

On Python 3 you can do the following:

>>> a, b, *_ = 1, 3, 4, 5
>>> a
1
>>> b
3

_ is just a place holder for values you don't need

jamylak
  • 128,818
  • 30
  • 231
  • 230
6

You could use _ to represent variables you wanted to "throw away"

>>> a, b, _ = 1, 3, 4
>>> a
1
>>> b
3
Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
  • 2
    Thanks! but it won't work when there're more element ``a,b,_ = 1,3,4,5`` – Hanfei Sun Jul 07 '12 at 00:19
  • 1
    @Firegun you're right, you would have to do something like `a, b, _, _ = 1, 3, 4, 5` which gets ugly fast. Honestly I think just getting a list and using `[:2]` makes more sense and is more pythonic. – Nolen Royalty Jul 07 '12 at 00:31
  • 1
    This method works well if it is not an explicit slice you are getting, eg `(x,_,z,h) = coord` instead of `(x,z,h) = coord[:1]+coord[2:]`. For larger tuples, you end up with stuff like `(_,_,c,_,e,f,_) = something`, which is arguably better than having a mess of index accesses. – Zoey Hewll Jun 02 '16 at 03:41
4

Or in Python 3.x you could do this:

  a, *b = 1, 3, 4

giving you:

In [15]: a
Out[15]: 1

In [16]: b
Out[16]: [3, 4]

It would avoid the exception, though you would have to parse b. This assume that you only want to have two variables on the left of the =, otherwise you could use

a, b, *ignore = ....

with v3.x

Levon
  • 138,105
  • 33
  • 200
  • 191