Skip to content

Instantly share code, notes, and snippets.

@kylecampbell
Last active February 1, 2019 18:57
Show Gist options
  • Select an option

  • Save kylecampbell/606ddde96f16ab20658adcbe19892b2c to your computer and use it in GitHub Desktop.

Select an option

Save kylecampbell/606ddde96f16ab20658adcbe19892b2c to your computer and use it in GitHub Desktop.
Flatten List of Lists
# METHOD 1 vs. METHOD 2
# test sample
l = [[1,2,3],[4,5,6], [7], [8,9]]*99
# METHOD 1: List Comprehension (slower)
flat_list = [item for sublist in l for item in sublist]
# tested in .ipynb with %timeit
# METHOD 2: itertools chain (~2x faster)
from itertools import chain
flat_list = list(chain.from_iterable(l))
# tested in .ipynb with %timeit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment