Python: Flatten a shallow list
Python List: Exercise - 23 with Solution
Flatten Shallow List
Write a Python program to flatten a shallow list.
Example - 1 :
Example - 2 :
Example - 3 :
Sample Solution-1:
Python Code:
# Import the 'itertools' module, which provides various functions for working with iterators
import itertools
# Define a list 'original_list' containing nested sublists
original_list = [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]]
# Use 'itertools.chain' and the unpacking operator (*) to merge the sublists into a single flat list
new_merged_list = list(itertools.chain(*original_list))
# Print the newly merged list 'new_merged_list'
print(new_merged_list)
Sample Output:
[2, 4, 3, 1, 5, 6, 9, 7, 9, 0]
Sample Solution-2:
Use a list comprehension to extract each value from sub-lists in order.
Python Code:
# Define a function named 'flatten' that takes a list of lists 'nums' and flattens it into a single list
def flatten(nums):
# Use a list comprehension to iterate through the sublists 'y' and the elements 'x' within each sublist
return [x for y in nums for x in y]
# Define a list 'nums' containing nested sublists
nums = [[1, 2, 3, 4], [5, 6, 7, 8]
print("Original list elements:")
# Print the original list 'nums'
print(nums)
# Print a newline for separation
print("\nFlatten the said list:")
# Call the 'flatten' function to flatten the 'nums' list and print the result
print(flatten(nums)
# Reassign 'nums' with a different list of nested sublists
nums = [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]]
print("\nOriginal list elements:")
# Print the original list 'nums'
print(nums)
# Print a newline for separation
print("\nFlatten the said list:")
# Call the 'flatten' function to flatten the new 'nums' list and print the result
print(flatten(nums))
Sample Output:
Original list elements: [[1, 2, 3, 4], [5, 6, 7, 8]] Flatten the said list: [1, 2, 3, 4, 5, 6, 7, 8] Original list elements: [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]] Flatten the said list: [2, 4, 3, 1, 5, 6, 9, 7, 9, 0]
Flowchart:
Python Code Editor:
Previous: Write a Python program to find the index of an item in a specified list.
Next: Write a Python program to append a list to the second list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics