Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"ValueError too many values to unpack" when using str.split in a for loop

I've gotten this error before where the cause was obvious, but I'm having trouble with this snippet below.

#!/usr/bin/python

ACL = 'group:troubleshooters:r,user:auto:rx,user:nrpe:r'

for e in ACL.split(','):
  print 'e = "%s"' % e
  print 'type during split = %s' % type(e.split(':'))
  print 'value during split:  %s' % e.split(':')
  print 'number of elements:  %d' % len(e.split(':'))
  for (one, two, three) in e.split(':'):
      print 'one = "%s", two = "%s"' % (one, two)

I've added those print statements for debugging, and have confirmed that the split is producing a 3-element list, but when I try to put that into 3 variables, I get:

e = "group:troubleshooters:r"
type during split = <type 'list'>
value during split:  ['group', 'troubleshooters', 'r']
number of elements:  3
Traceback (most recent call last):
  File "/tmp/python_split_test.py", line 10, in <module>
for (one, two, three) in e.split(':'):
ValueError: too many values to unpack

What am I missing?

like image 354
Jeremy Koppel Avatar asked Dec 13 '22 17:12

Jeremy Koppel


2 Answers

Maybe you should:

one, two, three = e.split(":")

as e.split(":") is already an iterable with three values.

If you write

for (one, two, three) in something

Then something must be an iterable of iterable of three values, e.g. [[1, 2, 3], [4, 5, 6]], but not [1, 2, 3].

like image 184
iBug Avatar answered Dec 29 '22 10:12

iBug


for (one, two, three) in e.split(':'):

requires e.split() to return a list of iterables (e.g. a 2-dimensional list). for will iterate over the list, and assign each element of the nested list to the coresponding variables during that iteration.

But e.split() just returns a single list of strings. You don't need to iterate, just assign them:

one, two, three = e.split(':')
like image 40
Barmar Avatar answered Dec 29 '22 11:12

Barmar