Skip to content
Advertisement

Iterating Through List of Lists, Maintaining List Structure

Say I have the following list of list of names:

JavaScript

I want to return only the “Matts” in the list, but I also want to maintain the list of list structure. So I want to return:

JavaScript

I’ve something like this, but this will append everthting together in one big list:

JavaScript

I know something like this is possible, but I want to avoid iterating through lists and appending. Is this possible?

JavaScript

Advertisement

Answer

Use a nested list comprehension, as below:

JavaScript

Output

JavaScript

The above nested list comprehension is equivalent to the following for-loop:

JavaScript

A third alternative functional alternative using filter and partial, is to do:

JavaScript

Micro-Benchmark

JavaScript

Setup (of micro-benchmarks)

JavaScript

Full Benchmark

Candidates

JavaScript

Plot Plot of alternative solutions

The above results were obtained for a list that varies from 100 to 1000 elements where each element is a list of 10 strings chosen at random from a population of 14 strings (names). The code for reproducing the results can be found here. As it can be seen from the plot the most performant solution is the one from @rv.kvetch.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement