Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Last active September 16, 2017 23:04
Show Gist options
  • Save Swarchal/60c852004497be404c179ba55196c011 to your computer and use it in GitHub Desktop.
Save Swarchal/60c852004497be404c179ba55196c011 to your computer and use it in GitHub Desktop.
list comprehension tutorial
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# list comprehensions\n",
"\n",
"*are awesome*\n",
"\n",
"Creating a list with a loop."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out_list = []\n",
"\n",
"for i in range(10):\n",
" out_list.append(i)\n",
" \n",
"out_list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As a list comprehension:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out_list = [i for i in range(10)]\n",
"\n",
"out_list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can use conditionals within them\n",
"\n",
"I.e a list of even numbers"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"even_nums = []\n",
"for i in range(20):\n",
" if i % 2 == 0:\n",
" even_nums.append(i)\n",
" \n",
"even_nums"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"even_nums = [i for i in range(20) if i % 2 == 0]\n",
"\n",
"even_nums"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can use functions within them"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def is_prime(n):\n",
" if n < 2:\n",
" return False\n",
" if n == 2: \n",
" return True \n",
" if not n & 1: \n",
" return False\n",
" for x in range(3, int(n**0.5) + 1, 2):\n",
" if n % x == 0:\n",
" return False\n",
" return True"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[2,\n",
" 3,\n",
" 5,\n",
" 7,\n",
" 11,\n",
" 13,\n",
" 17,\n",
" 19,\n",
" 23,\n",
" 29,\n",
" 31,\n",
" 37,\n",
" 41,\n",
" 43,\n",
" 47,\n",
" 53,\n",
" 59,\n",
" 61,\n",
" 67,\n",
" 71,\n",
" 73,\n",
" 79,\n",
" 83,\n",
" 89,\n",
" 97]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"primes = [i for i in range(100) if is_prime(i)]\n",
"\n",
"primes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can use nested list comprehensions.\n",
"\n",
"E.g if we want to create a list of lists of all combinations of two lists"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[['red', 'S'],\n",
" ['red', 'M'],\n",
" ['red', 'L'],\n",
" ['blue', 'S'],\n",
" ['blue', 'M'],\n",
" ['blue', 'L']]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"colours = [\"red\", \"blue\"]\n",
"sizes = [\"S\", \"M\", \"L\"]\n",
"\n",
"t_shirts = [[colour, size] for colour in colours for size in sizes]\n",
"\n",
"t_shirts"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[['red', 'S'],\n",
" ['red', 'M'],\n",
" ['red', 'L'],\n",
" ['blue', 'S'],\n",
" ['blue', 'M'],\n",
" ['blue', 'L']]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"t_shirts = []\n",
"\n",
"for colour in colours:\n",
" for size in sizes:\n",
" t_shirts.append([colour, size])\n",
" \n",
"t_shirts"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As pointed out by Jon, list comprehensions can also be used to flatten a nested list."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['red', 'S', 'red', 'M', 'red', 'L', 'blue', 'S', 'blue', 'M', 'blue', 'L']"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"flat = [i for sublist in t_shirts for i in sublist]\n",
"flat"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['red', 'S', 'red', 'M', 'red', 'L', 'blue', 'S', 'blue', 'M', 'blue', 'L']"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# as a loop\n",
"flat = []\n",
"for sublist in t_shirts:\n",
" for i in sublist:\n",
" flat.append(i)\n",
"flat"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dict comprehensions\n",
"\n",
"The same technique can also be used to create dictionaries"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"names = [\"Tim\", \"Angela\", \"Bob\"]\n",
"fav_food = [\"chips\", \"pizza\", \"wasabi?\"]\n",
"\n",
"my_dict = {name:food for name, food in zip(names, fav_food)}"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'Angela': 'pizza', 'Bob': 'wasabi?', 'Tim': 'chips'}"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment