1

This is my attempt to create a function that takes an irregular list of this type

cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['last cherry', None]]]]]

and print its elements one by one. I thought of flattening it by creating a second list. I have also tried comprehensions . Can someone provide some help?

def pick_cherries(field):
    flat = sum(field, [])
        i = 0
        while flat[i] != None:
            print(flat[i])
            i += 1
  • 2
    You say your lists are "irregular", but there's a very strong pattern in the example list you show. Is your list always of that structure, with the values in the first index of each list, and the "rest" of the structure in the second index? Because that's quite a bit easier to handle than a generic nested list. – Blckknght Jan 05 '22 at 01:55

2 Answers2

0

You could recursively call a flattening function:

cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['last cherry', None]]]]]

def flatten(input_list):
    result = []
    for item in input_list:
        if isinstance(item, list):
            # flatten returns a flat list, extend appends 
            # the contents of this list to the end of result
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

This outputs

['cherry1', 'cherry2', 'cherry3', 'cherry4', 'last cherry', None]

You can then just print each item in the result. Here, we are simply recursively flattening any encountered lists, with the base case being an item that is not a list, and therefore is just appended.

For a lazier approach that does not involve creating a new list, you can use a generator:

def flatten(input_list):
    for item in input_list:
        if isinstance(item, list):
            for yielded_item in flatten(item):
                yield yielded_item
        else:
            yield item

Then simply write:

for item in flatten(cherry_field):
    print(item)
Kraigolas
  • 5,121
  • 3
  • 12
  • 37
0

You can use recursion to accomplish this. Check for the type, if the type is a list, use recursion, otherwise add to an accumulator list.

data = [
  "cherry1", 
  [
    "cherry2", 
    [
      "cherry3", 
      [
        "cherry4", 
        [
          "last cherry", 
          None
        ]
      ]
    ]
  ]
]

def flatten(array: list, accumulator: list = []):
  for item in array:
    if isinstance(item, list):
      flatten(item, accumulator)
    else:
      accumulator.append(item)
  return accumulator

print(flatten(data))
# ['cherry1', 'cherry2', 'cherry3', 'cherry4', 'last cherry', None]
Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41