Skip to content

Instantly share code, notes, and snippets.

@mccurcio
Last active December 19, 2021 18:06
Show Gist options
  • Save mccurcio/af96859e16d40f7593d96dc21cabe959 to your computer and use it in GitHub Desktop.
Save mccurcio/af96859e16d40f7593d96dc21cabe959 to your computer and use it in GitHub Desktop.
List comprehension
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"source": "List comprehension"
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "mylist = [100, 200, 300, 400, 500]\n\n#Beginner way\nresult = []\nfor x in mylist:\n if x > 250:\n result.append(x)\nprint(result) # [300, 400, 500]\n\n#One Line Way\nresult = [x for x in mylist if x > 250]\nprint(result) # [300, 400, 500]",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3 (ipykernel)",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.8.8",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"gist": {
"id": "",
"data": {
"description": "List comprehension example",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment