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.

TomCho
  • 3,204
  • 6
  • 32
  • 83
  • [This question](http://stackoverflow.com/a/10532492/2003420) 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. – El Bert Feb 05 '15 at 11:00

1 Answers1

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.

Community
  • 1
  • 1
VHarisop
  • 2,816
  • 1
  • 14
  • 28
  • 1
    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 Hatarist Feb 05 '15 at 10:57
  • @Igor i was unaware of its compatibility, thanks. I edited the post accordingly. – VHarisop Feb 05 '15 at 10:59
  • 1
    No problem :) There's also a detailed explanation on extended unpacking: http://stackoverflow.com/questions/6967632/unpacking-extended-unpacking-and-nested-extended-unpacking. It's a really neat feature in py3k, I wish I used it more :( – Igor Hatarist Feb 05 '15 at 11:01
  • 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. – TomCho Feb 05 '15 at 11:35