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



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Given a predicate function, fn, and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate:

Example:

def tips_check_prop(fn, prop):
  return lambda obj: fn(obj[prop])
check_age = tips_check_prop(lambda x: x >= 25, 'age')
user = {'name': 'Owen', 'age': 25}

print(check_age(user))

Output:

True 

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook