Flatten a List

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, a list can contain other lists as elements. This is known as a nested list. Sometimes, we may need to flatten a nested list into a single list. In this challenge, you will be asked to write a function that flattens a list of lists once.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13641{{"`Flatten a List`"}} python/for_loops -.-> lab-13641{{"`Flatten a List`"}} python/list_comprehensions -.-> lab-13641{{"`Flatten a List`"}} python/lists -.-> lab-13641{{"`Flatten a List`"}} python/tuples -.-> lab-13641{{"`Flatten a List`"}} python/function_definition -.-> lab-13641{{"`Flatten a List`"}} end

Flatten a List

Write a Python function called flatten(lst) that takes a list of lists as an argument and returns a flattened list. The function should only flatten the list once, meaning that any nested lists within the original list should be flattened, but any nested lists within those nested lists should remain intact.

To solve this problem, you can use a list comprehension to extract each value from sub-lists in order.

def flatten(lst):
  return [x for y in lst for x in y]
flatten([[1, 2, 3, 4], [5, 6, 7, 8]]) ## [1, 2, 3, 4, 5, 6, 7, 8]

Summary

In this challenge, you learned how to write a Python function to flatten a list of lists once. You used a list comprehension to extract each value from sub-lists in order. This is a useful skill to have when working with nested lists in Python.

Other Python Tutorials you may like