Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Assign variables from array

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?

like image 322
Bijan Avatar asked Oct 06 '15 17:10

Bijan


2 Answers

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
like image 164
Cory Kramer Avatar answered Nov 17 '22 15:11

Cory Kramer


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)
like image 1
dawg Avatar answered Nov 17 '22 15:11

dawg