1

I'm trying to find a better and more pythonic way to this piece of code:

for i in rows:
    row_data = i.findAll('td')
    serial = row_data[0]
    hostname = row_data[1]
    owner = row_data[2]
    memory = row_data[3]
    processor = row_data[4]
    os = row_data[5]
    model = row_data[6]
    ip = row_data[7]

i'm trying to do something like this:

 [serial, hostname, owner, memory, etc..] = row_data[:7]

Any ideas on how this can be achieved?

With or without index i get this message: [serial, hostname, owner, memory, processor, os, model, be_ip] = row_data ValueError: too many values to unpack

1 Answer 1

6

You can do exactly that:

>>> row_data = ['serial', 'hostname', 'ip']
>>> [serial, hostname, ip] = row_data
>>> serial
'serial'
>>> hostname
'hostname'
>>> ip
'ip'

The square brackets around [serial, hostname, ip] are optional.

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

8 Comments

Worth mentioning that it's called unpacking
Maybe worth mentioning that a,b,*tail = (1,2,3,4) also works fine.
@Hyperboreus, is that version dependent? (It didn't work and I'm on 2.7.6)
@wnnmaw My bad, seems to be python3 only.
|

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.