6

I have some code in Python:

repost_pid = row[0]
repost_permalink = row[1]
repost_domain = row[2]
repost_title = row[3]
repost_submitter = row[4]

Is there a one-liner way to assign these variables?

Also, what would I do if I wanted to skip a value?

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Bijan
  • 7,737
  • 18
  • 89
  • 149

3 Answers3

14

Yes you can separate each variable with a , to perform unpacking

repost_pid, repost_permalink, repost_domain, repost_title, repost_submitter = row

If there is a particular value that you are not concerned about, the convention is to assign it to an underscore variable, e.g.

repost_pid, repost_permalink, _, repost_title, repost_submitter = row
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Great! Suppose I want to skip a value (i.e. I dont want row[2]), what would I put for its value? – Bijan Oct 06 '15 at 17:28
  • Note that this assumes there are no further entries in `row`. – Sven Marnach Oct 06 '15 at 17:28
  • @Bijan you need to mention that in your question. – Avinash Raj Oct 06 '15 at 17:29
  • @Bijan a `_`, by convention: `foo, _, bar = [1, 2, 3]`. – jonrsharpe Oct 06 '15 at 17:29
  • 2
    @Bijan: Anything but `_`. While some people use that as a convention, it's not a good idea. – Sven Marnach Oct 06 '15 at 17:30
  • (And the reason it is not a good idea is because it is common to do `from gettext import gettext as _` when doing i18n. Using it as a dummy variable would break translations) – spectras Oct 06 '15 at 17:45
  • @spectras: A more important reason not to use it is that it is pretty opaque. Almost everyone who encounters this for the first time mistakes it as some special syntax (as it is in e.g. Haskell), which it isn't. It's just a somewhat weird variable name. Using `unused_doamin` or whatever documents much better what's going on, won't confuse anyone, won't conflict with the gettext alias and is supported by all common linters, so they won't warn about the unused variable. – Sven Marnach Oct 06 '15 at 20:13
1

If you want to skip a value in sequence unpacking, you can do:

>>> row
[0, 1, 2, 3]
>>> r0,r1,r3=row[0:2]+[row[3]]
>>> r0,r1,r3
(0, 1, 3)
dawg
  • 98,345
  • 23
  • 131
  • 206
0
repost_pid,repost_permalink, repost_domain, repost_title, repost_submitter = row[0], row[1], row[2], row[3], row[4]

but it won't be readable

Ali Faki
  • 3,928
  • 3
  • 17
  • 25