In this Python list program, we will take a user input as a nested list and flatten given nested list structure with the help of the below-given steps.
Flatten given nested list:
Steps to solve the program
- Take a nested list as input.
- Flatten given nested into a single list using for loop.
- If the iterated element is a list then add the elements in that list to the empty list.
- Use the type() function to check for list type.
- If not then also add the element to the empty list.
- Print the list to see the result.
#Input lists
list1 = [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
list2 = []
for value in list:
if type(value) is list:
for var in value:
list2.append(var)
else:
list2.append(value)
#Printing output
print(list2)
Output :
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
Related Articles
Python program to convert tuples in the list into a sublist.
Python program to create a dictionary from a sublist in a given list.
Python program to replace ‘Java’ with ‘Python’ from the given list.
Python program to convert the 3rd character of each word to a capital case from the given list.
Python program to remove the 2nd character of each word from a given list.
Python program to get a length of each word and add it as a dictionary from the given list.