1

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.

1
  • This question shows one way of doing it in Python 3 - the same way suggest in one of the answers. But not way in Python 2 seems to do want you're asking. Commented Feb 5, 2015 at 11:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Note that it's only compatible with python 3. Otherwise I guess adding a new line that covers the whole line.replace ... split() routine isn't a poor choice.
@Igor i was unaware of its compatibility, thanks. I edited the post accordingly.
No problem :) There's also a detailed explanation on extended unpacking: stackoverflow.com/questions/6967632/…. It's a really neat feature in py3k, I wish I used it more :(
Thanks for the reading suggestions. Unpacking in py3k is neat. Too bad I can't import that syntax into py2. I guess I'll just add one more line to the code, like @IgorHatarist suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.