Home »
Python »
Python programs
Flattening a shallow list in Python
Learn about the Flattening a shallow list in Python.
Submitted by Nijakat Khan, on July 15, 2022
Here the task is to flatten a list.
Assume input is
[[2, 3, 4], [3, 2, 4], [5, 8]]
We have to convert it in a single list
Output is
[2, 3, 4, 3, 2, 4, 5, 8]
For flattening a shallow list, we can use the following methods,
Method 1: By using the for loop
In python, the for loop is used to iterate the sequence of elements (list, tuple, dictionary, etc.). Here we can also define the range in for loop its syntax is different from the for loop of c programming language but can say that it is like for each loop.
Syntax:
for variable in sequence:
# Loop operations
Example 1:
# list
city_list=[["Gwalior","Bhopal"], ["Delhi","Indore"], ["Noida"]]
new_city_list= []
# We are applying here nested for loop
for x in city_list:
for y in x:
new_city_list.append(y)
print(new_city_list)
Output:
['Gwalior', 'Bhopal', 'Delhi', 'Indore', 'Noida']
Method 2: By using the chain() method
The chain() method is a Python method that takes the sequence and returns one by one and then groups all the elements and converts it into a single variable.
To use chain() we have to import the "itertools" module.
Syntax:
chain(* list)
Example 2:
from itertools import chain
city_list=[["Gwalior","Bhopal"], ["Delhi","Indore"], ["Noida"]]
new_list=(list(chain(*city_list)))
print(new_list)
Output:
['Gwalior', 'Bhopal', 'Delhi', 'Indore', 'Noida']
Method 3: By joining the list of lists
We can also join the list of lists using a function and in the function, we can use yield.
Function:
The function is a technique that reduces the size of the program if we are working on a large project. we can call the function anywhere anytime it provides the reusability of code we have to write code once and can use that code multiple times
Syntax:
def functionname([arguments]):
# Operations which we have to perform
# in function
Here arguments are optional according to the requirements.
yield: The yield is the same as the return in python. Both are used to return the value of a function. yield converts the normal function into the generator. it can run multiple times while return can run an only a single time.
Example 3:
# We have created a function named join
def join(l):
for i in l:
for j in i:
yield j
record= [[1,2,3,4], [5,6], [7,8,9]]
# Here we have called the function
# that we have created
j=list(join(record))
print(j)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Python List Programs »