Created
June 16, 2023 07:23
-
-
Save kr-stn/496ecbd4b1a8026762daa9373cb8baf4 to your computer and use it in GitHub Desktop.
Speed comparison of Python for loop vs. list comprehension
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
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 22, | |
"id": "ce2bf989", | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import random\n", | |
"randomlist = []\n", | |
"for i in range(0, 100000):\n", | |
" n = random.randint(0, 2)\n", | |
" randomlist.append(n)\n", | |
"#print(randomlist)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 23, | |
"id": "1ce8d7ef", | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"def split_data_loop(data):\n", | |
" a = []\n", | |
" b = []\n", | |
" c = []\n", | |
" for d in data:\n", | |
" if d == 0 : a.append(d)\n", | |
" if d == 1: b.append(d)\n", | |
" if d == 2 : c.append(d)\n", | |
"\n", | |
" return a, b, c" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 24, | |
"id": "a607ad8a", | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"def split_data_list(data):\n", | |
" a = [d for d in data if d == 0]\n", | |
" b = [d for d in data if d == 1]\n", | |
" c = [d for d in data if d == 2]\n", | |
"\n", | |
" return a, b, c" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 25, | |
"id": "7655a7eb", | |
"metadata": { | |
"scrolled": true | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"11 ms ± 25.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" | |
] | |
} | |
], | |
"source": [ | |
"%timeit split_data_list(randomlist)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 26, | |
"id": "0d60b611", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"11 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" | |
] | |
} | |
], | |
"source": [ | |
"%timeit split_data_loop(randomlist)" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3 (ipykernel)", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.10.9" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment