Search code examples
pythonpython-3.xiterable-unpacking

Unpacking nested tuples using list comprehension


I have a list:

path = [
    (5, 5),
    'Start',
    0,
    ((5, 4), 'South', 1),
    ((5, 3), 'South', 1),
    ((4, 3), 'West', 1),
    ((4, 2), 'South', 1),
    ((3, 2), 'West', 1),
    ((2, 2), 'West', 1),
    ((2, 1), 'South', 1),
    ((1, 1), 'West', 1)]

I am trying to extract all the directions (except for the first one that says 'Start') so that I have a new list:

directions = ['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']

I have tried the following:

for (x, y), direction, cost in path[1:]:  # [1:] to omit the first direction
     directions.append(direction)

The result is: ValueError: too many values to unpack (expected 3)

I have also tried unpacking by using the following:

result = [(x, y, direction, cost) for (x, y), direction,cost in path[1:]]

It gives the same error. The tuple within a tuple within a list is really confusing me. Thanks in advance for any insight, I greatly appreciate it!


Solution

  • I just reformatted the code in the question for readability and accidentally made the problem a lot more obvious: The first three elements of the list aren't in a tuple. Use path[3:] instead of path[1:].

    The reason you're getting that error "too many values" is that it's trying to unpack 'Start', which is 5 long, not 3.

    >>> [direction for (_x, _y), direction, _cost in path[3:]]
    ['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']