w3resource

Python: Flatten a shallow list

Python List: Exercise - 23 with Solution

Write a Python program to flatten a shallow list.

Example - 1 :

Python: Flatten a shallow list

Example - 2 :

Python: Flatten a shallow list

Example - 3 :

Python: Flatten a shallow list

Sample Solution-1:

Python Code:

import itertools
original_list = [[2,4,3],[1,5,6], [9], [7,9,0]]
new_merged_list = list(itertools.chain(*original_list))
print(new_merged_list)

Sample Output:

[2, 4, 3, 1, 5, 6, 9, 7, 9, 0] 

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Sample Solution-2:

Use a list comprehension to extract each value from sub-lists in order.

Python Code:

def flatten(nums):
  return [x for y in nums for x in y]
nums = [[1, 2, 3, 4], [5, 6, 7, 8]]
print("Original list elements:")
print(nums) 
print("\nFlatten the said list:")
print(flatten(nums))
nums = [[2,4,3],[1,5,6], [9], [7,9,0]]
print("\nOriginal list elements:")
print(nums) 
print("\nFlatten the said list:")
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:

Flowchart: Flatten a shallow list

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

Big Number Readability:

you can separate zeros with underscore (_)

print(2_000_000)
print(2_000_000 +1)

Output:

2000000
2000001