1

For instance, I could have this list:

l = [1, [2, 3], [4, 5, [6, 7], 8]]

and I want to flatten the list like this:

l = [1, 2, 3, 4, 5, 6, 7, 8]

I found some methods online for doing this, but they assume that the list doesn't contain any values outside of sub-lists, or have side effects like reversing the order of elements. What's the best way to do this?

[Edit] I got an existing question recommended, but I couldn't understand what "yield from" does in Python, as I haven't seen it before in that context.

haley
  • 845
  • 1
  • 7
  • 15

1 Answers1

1
# initializing the data and empty list
data = [1, [2, 3, [4, 5]], 6, [[7], [8, 9]]]
flat_list = []

# function
def flatten_list(data):
    # iterating over the data
    for element in data:
        # checking for list
        if type(element) == list:
            # calling the same function with current element as new argument
            flatten_list(element)
        else:
            flat_list.append(element)

# flattening the given list
flatten_list(data)

# printing the flat_list
print(flat_list)

(See more at https://geekflare.com/flatten-list-python/)

CoderCookie10
  • 81
  • 1
  • 10