Home  >  Article  >  Backend Development  >  Expand list into individual elements using Python

Expand list into individual elements using Python

WBOY
WBOYforward
2023-09-08 23:57:03920browse

Expand list into individual elements using Python

List is a powerful data structure in Python that can hold many different types of values. We may encounter nested lists where the items themselves are lists. In this case, it may be crucial to flatten the list and retrieve the individual elements from the hierarchy. In Python, we have some in-built functions - chain(), extend() and append() which can be used to solve the problem of flattening a list into a single element.

Let’s give an example:

enter

# Flatten List
my_list = [[11, 21, 31], [20, 30, 40], [4, 5, 6], [1, 2, 3]]

Output

# individual element in the list
[11, 21, 31, 20, 30, 40, 4, 5, 6, 1, 2, 3]

grammar

All examples use the following syntax -

itertools.chain()

itertools is the name of the module that provides the chain() built-in function. This function takes multiple iterators as arguments and returns a single iterator.

extend()

extend() is a built-in method in Python that is used to add a specific list element to the end of the current list.

append()

append() is a built-in method in Python that adds elements to the end of the list.

[[],[],[]]

The above representation illustrates the nested list structure.

Use nested loops

The program uses nested for loops to iterate over sublists and uses the append() method to help

Example

In the following example, the program is started by defining a function named flatten_list that accepts an argument of lst (to receive the value of the input list). Then create an empty list in the variable flattened which will store the list containing the individual elements. Next, use a nested for loop to iterate over each sublist in the list and use append() to convert the sublist into a single element. Then use the function return to get the new list. Now create the Flatten list in the variable nested_list and store it in the variable f_list using the same variable as the argument in the calling function. Finally, we print the result with the help of variable f_list.

def flatten_list(lst):
    flattened = []
    for sublist in lst:
        for item in sublist:
            flattened.append(item)
    return flattened

# Create the flattened list
nested_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
# Calling function used in the variable
f_list = flatten_list(nested_list)
print("The individual element in the list:\n", f_list)

Output

 The individual element in the list:
 [10, 20, 30, 40, 50, 60, 70, 80, 90]

Use list comprehension

This program uses a list comprehension, where nested for loops are implemented to convert a Flatten List into individual elements.

Example

In the following example, you start your program by defining a function named flatten_list that accepts a parameter named lst that stores the values ​​of the input list. The function is then returned using a list comprehension, with a nested for loop iterating into the sublists. Next, create the flattened list and store it in the variable n_list. Then use the calling function in the variable f_list and use the same variable in the print function to get the result.

def flatten_list(lst):
    return [item for sublist in lst for item in sublist]

# Create the flatten list
n_list = [[11, 21, 31], [41, 51, 61], [71, 81, 91]]
# calling function used in the variable
f_list = flatten_list(n_list)
print("The individual element in the list:\n", f_list)

Output

 The individual element in the list:
 [11, 21, 31, 41, 51, 61, 71, 81, 91]

Use itertools.chain() function

This is a Python program that uses the itertools module to flatten nested lists. The flatten_list function takes a nested list as argument and returns a new list containing all the elements in the sublist. The itertools.chain function combines all sublists into an iterable object, which is then converted to a list using the list function. The program then creates a nested list called nested_list, calls the flatten_list function using the list as an argument, and assigns the result to the variable flattened_list.

Example

In the example below, start the program by importing a module called itertools, which will help convert flat lists into individual elements. Then start creating the function flatten_list

that accepts the parameter lst
import itertools
def flatten_list(lst):
    return list(itertools.chain(*lst))
# Create the flatten list
nested_list = [[12, 22, 32], [42, 52, 62], [72, 82, 92]]
# Calling function used in the variable
flattened_list = flatten_list(nested_list)
print("The individual element in the list:\n", flattened_list)

Output

 The individual element in the list:
 [12, 22, 32, 42, 52, 62, 72, 82, 92]

Use recursion

This program uses a recursive function to handle flattening the list and uses the built-in function isintance() which will check the condition of the object type and help generate a flattened list of individual elements.

Example

In the following example, the program iteratively flattens the constructed list by extracting each element. It then prints a flattened list containing all the individual elements in the nested list.

def flatten_list(lst):
    emp_list = []
    for item in lst:
        if isinstance(item, list):
            emp_list.extend(flatten_list(item))
        else:
            emp_list.append(item)
    return emp_list


# Create the flatten list
nested_list = [[81, 82, 83], [84, 85, 86], [87, 88, 89, 99, 100]]
f_list = flatten_list(nested_list)
print("The individual element in the list:\n", f_list)

Output

 The individual element in the list:
 [81, 82, 83, 84, 85, 86, 87, 88, 89, 99, 100]

in conclusion

We discussed various ways to solve the problem statement. We see how flattening lists will give us an essential skill, allowing us to work with complex data structures and access individual elements more efficiently. Additionally, whether we are working on data processing, algorithmic problem solving, or any other Python programming assignment or task, knowing how to flatten a list can be useful.

The above is the detailed content of Expand list into individual elements using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete