Python chain to list

Python Itertools.chain.from_iterable() Function with Examples

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.chain.from_iterable() Function:

chain.from_iterable() belongs to the category of terminating iterators. This function takes a single iterable as an argument, and all of the elements of the input iterable must also be iterable, and it returns a flattened iterable containing all of the input iterable’s elements.

chain.from_iterable(iterable)

iterable: It could be any iterable like list, string, and so on.

Given List = ["good", "morning", "all"]
The flattened list of the given list: ['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g', 'a', 'l', 'l']
The flattened list of the given list: ['h', 'e', 'l', 'l', 'o', 'a', 'l', 'l']

Itertools.chain.from_iterable() Function with Examples in Python

Method #1: Using Built-in Functions (Static Input)

  • Import itertools module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the itertools.chain.from_iterable() function that returns a flattened list (list of characters) containing all of the given list elements.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the flattened list of the given list.
  • The Exit of the Program.
Читайте также:  Jquery input file php

Below is the implementation:

# Import itertools module using the import keyword. import itertools # Give the list as static input and store it in a variable. gvn_lst = ["good", "morning", "all"] # Pass the given list as an argument to the itertools.chain.from_iterable() # function that returns a flattened list (list of characters) containing all # of the given list elements. # Store it in another variable. rslt_chain = itertools.chain.from_iterable(gvn_lst) # Convert the above result into a list using the list() function and store it # in a variable. rslt_lst = list(rslt_chain) # Print the flattened list of the given list. print("The flattened list of the given list:") print(rslt_lst)
The flattened list of the given list: ['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g', 'a', 'l', 'l']
string and List as one input at a time
# Import itertools module using the import keyword. import itertools # Give the list as static input and store it in a variable. gvn_lst = ["hello", ['a', 'l', 'l']] # Pass the given list as an argument to the itertools.chain.from_iterable() # function that returns a flattened list (list of characters) containing all # of the given list elements. # Store it in another variable. rslt_chain = itertools.chain.from_iterable(gvn_lst) # Convert the above result into a list using the list() function and store it # in a variable. rslt_lst = list(rslt_chain) # Print the flattened list of the given list. print("The flattened list of the given list:") print(rslt_lst)
The flattened list of the given list: ['h', 'e', 'l', 'l', 'o', 'a', 'l', 'l']

Method #2: Using Built-in Functions (User Input)

  • Import itertools module using the import keyword.
  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the itertools.chain.from_iterable() function that returns a flattened list (list of characters) containing all of the given list elements.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the flattened list of the given list.
  • The Exit of the Program.
Читайте также:  Python функция подсчета символов в строке

Below is the implementation:

# Import itertools module using the import keyword. import itertools # Give the list as user input using list(),input(),and split() functions. # Store it in a variable. gvn_lst = list(input( 'Enter some random List Elements separated by spaces = ').split()) # Pass the given list as an argument to the itertools.chain.from_iterable() # function that returns a flattened list (list of characters) containing all # of the given list elements. # Store it in another variable. rslt_chain = itertools.chain.from_iterable(gvn_lst) # Convert the above result into a list using the list() function and store it # in a variable. rslt_lst = list(rslt_chain) # Print the flattened list of the given list. print("The flattened list of the given list:") print(rslt_lst)
Enter some random List Elements separated by spaces = python code The flattened list of the given list: ['p', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'd', 'e']

Источник

Python – Flatten a list of lists to a single list

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

How to flatten a list of lists?

There are a number of ways to flatten a list of lists in python. You can use a list comprehension, the itertools library, or simply loop through the list of lists adding each item to a separate list, etc. Let’s see them in action through examples followed by a runtime assessment of each.

1. Naive method – Iterate over the list of lists

Here, we iterate through each item of all the subsequent lists in a nested loop and append them to a separate list.

# flatten list of lists ls = [['a','b','c'],['d','e','f'],['g','h','i']] # iterate through list of lists in a nested loop flat_ls = [] for i in ls: for j in i: flat_ls.append(j) # print print("Original list:", ls) print("Flattened list:", flat_ls)
Original list: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Flattened list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

In the above example, the outer loop iterates over all the subsequent lists while the inner loop iterates over the items in each of the subsequent lists with each item being appended to the list flat_ls .

2. Using list comprehension

You can also use a list comprehension to basically do the same thing as in the previous step but with better readability and faster execution.

# flatten list of lists ls = [['a','b','c'],['d','e','f'],['g','h','i']] # using list comprehension flat_ls = [item for sublist in ls for item in sublist] # print print("Original list:", ls) print("Flattened list:", flat_ls)
Original list: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Flattened list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Here, we use list comprehension to create a flattened list by keeping each item of each of the sublists in the original list of lists. Using list comprehension is similar to nested looping but has better readability (in this use case) and is faster (which we’ll see later in the article).

3. Using the itertools library

The python itertools standard library offers handy functionalities for working with iterables. Here, we break the list of lists into individual parts and then chain them together into a single iterable.

import itertools # flatten list of lists ls = [['a','b','c'],['d','e','f'],['g','h','i']] # using itertools flat_ls = list(itertools.chain(*ls)) # print print("Original list:", ls) print("Flattened list:", flat_ls)
Original list: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Flattened list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

In the above example itertools.chain() function is used to join (or chain together) the iterables passed as parameters. Passing *ls to it results in the outer list to be unpacked as parameters which are then chained together. The following example illustrates this better.

ls1 = list(itertools.chain([1,2,3],[4,5],[6])) ls2 = list(itertools.chain(*[[1,2,3],[4,5],[6]])) print(ls1) print(ls2)

You can see that for ls1 we pass the iterables that we want to chain together as parameters to the itertools.chain() function. For ls2 , since we’re passing a single list of lists, we need to unpack it to its component iterables using * .

Alternatively, if you’re not comfortable with using * , you can use the itertools.chain.from_iterable() function which doesn’t require you to unpack your list.

ls3 = list(itertools.chain.from_iterable([[1,2,3],[4,5],[6]])) print(ls3)

Comparing the methods for runtime

Now let’s compare the different methods discussed above to flatten a list of lists for runtime.

%%timeit ls = [['a','b','c'],['d','e','f'],['g','h','i']] flat_ls = [] for i in ls: for j in i: flat_ls.append(j)
1.45 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit ls = [['a','b','c'],['d','e','f'],['g','h','i']] flat_ls = [item for sublist in ls for item in sublist]
1.12 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit ls = [['a','b','c'],['d','e','f'],['g','h','i']] flat_ls = list(itertools.chain(*ls))
875 ns ± 20.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Of the three methods discussed, we found using itertools.chain() to be the fastest and using a direct nested loop to be the slowest. List comprehensions are not only fast but can be intuitive and readable for such cases (where they’re short and simple).

With this, we come to the end of this tutorial. We discussed some of the common ways of flattening a list of lists in python along with their examples and runtime performances. There are, however, other methods as well. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel.

Tutorials on python lists:

  • Python – Check if an element is in a list
  • Python – Iterate over multiple lists in parallel using zip()
  • Python – Flatten a list of lists to a single list
  • Pandas DataFrame to a List in Python
  • Python – Convert List to a String
  • Convert Numpy array to a List – With Examples
  • Python List Comprehension – With Examples
  • Python List Index – With Examples
  • Python List Count Item Frequency
  • Python List Length
  • Python Sort a list – With Examples
  • Python Reverse a List – With Examples
  • Python Remove Duplicates from a List
  • Python list append, extend and insert functions.
  • Python list remove, pop and clear functions.

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью