Python sublists to list

How to get all sublists of a list in Python

In this post, we will learn how to print all sublists from a list in Python. The input of the program is a list and the output is a list holding all sublists. We will write one program that will take the list inputs one by one and print out the final output.

  • Take the total size of the list from the user.
  • Read the values one by one from the user.
  • Print out the final list of sublists.

Method 1: Get all sublists of a Python list with nested for loops:

We will use one nested for loop to find out all combinations of a list.

  • Run one loop in the range of 0 to length of the list.
  • Run one inner loop in the range of current outer loop to length of the list.
  • Get the slice of the list in between the current indices pointed by the outer loop and inner loop.
  • Add the sliced list to the final list.
  • Return the final list.

Below is the complete Python program:

= list() result_list = list() size = int(input('Enter the size of the list :')) print('Enter all elements of the list :') for i in range(size): given_list.append(int(input('Enter element to add : '))) for i in range(len(given_list) + 1): for j in range(i + 1, len(given_list) + 1): result_list.append(given_list[i:j]) print(given_list) print(result_list)
  • given_list is the original list entered by the user.
  • result_list is the final list i.e. lists of lists.
  • The size variable holds the size of the list. We are reading this value from the user.
  • The first for loop is used to read all values for the list one by one. We are using the input() method to read the values. Each value is converted to an integer with the int() method and appends to the list given_list .
  • The last nested for loops are used to create the final list. It uses list slicing to get the sublists.
  • At the end of the program, we are printing the original and the final lists.
Читайте также:  Html body default height

This program will print the below output:

list :3 Enter all elements of the list : Enter element to add : 1 Enter element to add : 2 Enter element to add : 3 [1, 2, 3] [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] Enter the size of the list :5 Enter all elements of the list : Enter element to add : 1 Enter element to add : 2 Enter element to add : 3 Enter element to add : 4 Enter element to add : 5 [1, 2, 3, 4, 5] [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2], [2, 3], [2, 3, 4], [2, 3, 4, 5], [3], [3, 4], [3, 4, 5], [4], [4, 5], [5]]

Method 2: Find the sublists of a list recursively:

This problem can also be solved recursively. With this approach, it will find the sublists of all the elements excluding the first element of the list recursively, append the elements with the first element and adds all to the final list.

def get_sublists(l): if len(l) == 0: return [[]] sublists = [] first = l[0] remaining = l[1:] sublist_remaining = get_sublists(remaining) for sublist in sublist_remaining: sublists.append([first] + sublist) sublists.extend(sublist_remaining) return sublists if __name__ == "__main__": given_list = list() result_list = list() size = int(input("Enter the size of the list: ")) print("Enter all elements of the list: ") for i in range(size): given_list.append(int(input("Enter element to add: "))) result_list = get_sublists(given_list) print(result_list)

Python get sublists from a list

list: 4 Enter all elements of the list: Enter element to add: 1 Enter element to add: 2 Enter element to add: 3 Enter element to add: 4 [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], []]

Источник

Python – Flatten a list of lists to a single list

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 .

Читайте также:  Java util list type

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).

Читайте также:  Check exception in php

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

Источник

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