본문 바로가기
개념/혼자 공부하는 파이썬

python) Explanation of the Flatten Functions

by kiseno 2024. 11. 4.
728x90
반응형
SMALL
def flatten(data):
    output = []
    for item in data:
        if type(item) == list:
            output += item
        else:
            output.append(item)
    return output

def flatten2(data):
    output=[]
    for item in data:
        if type(item) == list:
            output +=flatten2(item)
        else:
            output.append(item)
    return output

example = [[1,2,3],[4,[5,6]],[7,[8,9]]]
print("origin : ",example)
print("flattened : ",flatten(example))
print("flattened2 : ",flatten2(example))

### Explanation of the Flatten Functions

This code snippet features two functions designed to flatten nested lists in Python, but each with a different level of flattening capability. Let's dive into the details:

#### The `flatten` Function

- **Purpose**: To flatten a list one level deep. This means it only removes one layer of nesting in the list.
- **Mechanism**: It iterates through each item in the provided list (`data`). If an item is a list, it extends the `output` list by adding elements of this sublist directly. If the item is not a list, it appends the item to the `output` list.

#### The `flatten2` Function

- **Purpose**: To recursively flatten a list to all levels, removing all nesting.
- **Mechanism**: Similar to `flatten`, but when it encounters a list, it recursively calls itself (`flatten2`) to flatten the sublist. This approach ensures that all nested lists, no matter how deeply they are nested, get flattened.

#### Example and Output Analysis

- **`example = [[1,2,3],[4,[5,6]],[7,[8,9]]]`**: Defines a nested list with two levels of nesting in some parts.
- **`flatten(example)`** Output: `[1, 2, 3, 4, [5, 6], 7, [8, 9]]`. This demonstrates the one-level flattening capability of `flatten`. It does not flatten the nested lists `[5, 6]` and `[8, 9]`.
- **`flatten2(example)`** Output: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. This showcases the recursive flattening capability of `flatten2`, which removes all levels of nesting.

### Conclusion

- **Use `flatten`** when you need to reduce the nesting of a list by one level.
- **Use `flatten2`** for comprehensive flattening, eliminating all nesting within a list, no matter how deep.

728x90
반응형
LIST