TomCho
TomCho

Reputation: 3507

parse a list into variable and sublist - pythonic way

I am parsing a list into a variable and another list with this script:

b=[' 687.3774', ' 478.6', ' 47', ' 58', ' 96.90']
c,d=b[0],b[1:]

It is always the first element that would be separated and this code works fine, however, it repeats the list b on the right hand side. This is not a problem but it does get annoying when my b is something big like line.replace('*',',').replace(' ',',').split(','). This doesn't really look like the pythonic way of writing this down. I have read some posts in this forum and the documentation on tuples and etc but nothing quite did the trick for me. Below are some things that I tried in a "shot in the dark" manner and that obviously didn't work

d=[]
c,d[:]=b
c,list(d)=b
c,d=b[0],[1:]

I am also aware of the b.pop method but I could not find a method to use that without repeating b in the RHS.

Help is appreciated. Thank you.

Upvotes: 1

Views: 200

Answers (1)

VHarisop
VHarisop

Reputation: 2826

In Python 3, you can try

c, *d = b

It will assign b[0] to c and the rest to d. You should see this question's answers for an explanation on how the * operator works on sequences.

Upvotes: 2

Related Questions