Skip to content

Instantly share code, notes, and snippets.

@pdbartsch
Last active February 26, 2024 02:47
Show Gist options
  • Save pdbartsch/d527e1a0ad9e6c04613f8e355e1de0fa to your computer and use it in GitHub Desktop.
Save pdbartsch/d527e1a0ad9e6c04613f8e355e1de0fa to your computer and use it in GitHub Desktop.
Learn Python - List Comprehension
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "623c5b3f",
"metadata": {},
"source": [
"# List Comprehension in Python"
]
},
{
"cell_type": "markdown",
"id": "83507115",
"metadata": {},
"source": [
"### Archived copy in case you'd like to follow along\n",
"- [On NBViewer](https://nbviewer.org/gist/pdbartsch/d527e1a0ad9e6c04613f8e355e1de0fa)"
]
},
{
"cell_type": "markdown",
"id": "4980f7eb",
"metadata": {},
"source": [
"### Jupyter Notebooks:\n",
"- Create, edit, share and execute live code along with\n",
"- Narrative text written in Markdown\n",
"- Can make use of environments\n",
"\n",
"#### Options:\n",
"- Install locally\n",
" - `pip install notebook`\n",
" - `jupyter notebook` To run the notebook\n",
"- https://jupyter.org/try\n",
"- https://colab.research.google.com/\n"
]
},
{
"cell_type": "markdown",
"id": "e75cd566",
"metadata": {},
"source": [
"## List Comprehension\n",
"- a concise way to create lists\n",
"- can sometimes be used in place of a for loop\n",
"- [Python List Comprehensions: Explained Visually](https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/)\n",
"- [Python docs - List Comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)\n",
"- [Jupyter Notebook Shortcuts](https://towardsdatascience.com/jypyter-notebook-shortcuts-bf0101a98330) \n",
"---"
]
},
{
"cell_type": "markdown",
"id": "8cde1f04",
"metadata": {},
"source": [
"### Example from Python docs:\n",
"##### Regular for loop"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "8cd9bc22",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n"
]
}
],
"source": [
"squares = []\n",
"for x in range(10):\n",
" squares.append(x**2)\n",
"print(squares)"
]
},
{
"cell_type": "markdown",
"id": "7628fe9c",
"metadata": {},
"source": [
"##### Equivalent using list comprehension"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7f589f34",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n"
]
}
],
"source": [
"squares_lc = [x**2 for x in range(10)]\n",
"print(squares_lc)"
]
},
{
"cell_type": "markdown",
"id": "2eeaa10e",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"id": "771c6c5f",
"metadata": {},
"source": [
"### More examples of list comprehensions"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "4a7f7d18",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n"
]
}
],
"source": [
"first_fifteen_numbers = [i for i in range(1, 16)]\n",
"print(first_fifteen_numbers)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "0203edac",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 2, 4, 6, 8, 10]\n"
]
}
],
"source": [
"even_numbers = [i for i in range(11) if i % 2 == 0]\n",
"print(even_numbers)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "b1b39ead",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 3, 5, 7, 9]\n"
]
}
],
"source": [
"odd_numbers = [i for i in range(11) if i % 2 != 0]\n",
"print(odd_numbers)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "3afe6a4e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]\n"
]
}
],
"source": [
"every_fifth = [i for i in range(0,51,5)] #range(start, stop, step)\n",
"print(every_fifth)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "91d07c4e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['c', 'f', 'i', 'l', 'o', 'r', 'u', 'x']\n"
]
}
],
"source": [
"alphabet = 'abcdefghijklmnopqrstuvwxyz'\n",
"every_third_letter = [alphabet[i] for i in range(2, len(alphabet), 3)]\n",
"print(every_third_letter)"
]
},
{
"cell_type": "markdown",
"id": "27bc440f",
"metadata": {},
"source": [
"#### Nested List Comprehension"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "4259052a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n"
]
}
],
"source": [
"pairs = [(i, j) for i in range(3) for j in range(3)]\n",
"print(pairs) #output is a list of tuples"
]
},
{
"cell_type": "markdown",
"id": "1bebedbd",
"metadata": {},
"source": [
"#### List Comprehension used on Dictionary"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "e34551a1",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['apple', 'banana', 'orange']\n"
]
}
],
"source": [
"prices = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}\n",
"\n",
"# extract all values from the dictionary\n",
"values = [price for price in prices.values()]\n",
"\n",
"# extract all keys from the dictionary\n",
"keys = [fruit for fruit in prices.keys()]\n",
"\n",
"print(keys)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "a42c685a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5 apple\n",
"0.25 banana\n",
"0.75 orange\n"
]
}
],
"source": [
"# use the zip() function to create a new iterable that contains pairs of corresponding elements from both lists\n",
"# for loop to iterate over this iterable and print out each pair of elements side by side\n",
"for i, j in zip(values, keys):\n",
" print(i, j)"
]
},
{
"cell_type": "markdown",
"id": "cb1dfa05",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"id": "7b8ebc41",
"metadata": {},
"source": [
"#### Some ideas for future python code topics:\n",
" - zip()\n",
" - enumerate()"
]
}
],
"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.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment