Last active
February 1, 2019 18:57
-
-
Save kylecampbell/606ddde96f16ab20658adcbe19892b2c to your computer and use it in GitHub Desktop.
Flatten List of Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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