Skip to content

Instantly share code, notes, and snippets.

@bkbncn
Last active February 16, 2025 02:49
Show Gist options
  • Save bkbncn/85b845b955cc6b4eb1d12442fb56df25 to your computer and use it in GitHub Desktop.
Save bkbncn/85b845b955cc6b4eb1d12442fb56df25 to your computer and use it in GitHub Desktop.
Python List Comprehension tutorial
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Based on https://www.machinelearningplus.com/python/list-comprehensions-in-python/"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Introduction\n",
"List comprehensions is a pythonic way of expressing a ‘for-loop’ that appends to a list in a single line of code.\n",
"\n",
"So how does a list comprehension look? Let’s write one to create a list of even numbers between 0 and 9:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 2, 4, 6, 8]"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[i for i in range(10) if i%2 == 0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And below is the for-loop equivalent for the same logic:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 2, 4, 6, 8]"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"result = []\n",
"for i in range(10):\n",
" if i%2 == 0:\n",
" result.append(i)\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I prefer list comprehensions because it’s easier to read, requires lesser keystrokes and it usually runs faster as well.\n",
"\n",
"The best way to learn list comprehensions is by studying examples of converting for-loops and practicing sample problems."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2. Typical format of List Comprehensions\n",
"A list comprehension typically has 3 components:\n",
"\n",
"- The output (which can be string, number, list or any object you want to put in the list.)\n",
"- For Statements\n",
"- Conditional filtering (optional).\n",
"\n",
"\n",
"Below is a typical format of a list comprehension.\n",
"\n",
"\n",
"$[[outpt \\space value] \\space for \\space (i \\space in \\space iterable) \\space if \\space (filter \\space conditions)]$\n",
"\n",
"However, this format is not a golden rule.\n",
"\n",
"Because there can be logics that can have multiple ‘for-statements’ and ‘if conditions’ and they can change positions as well. The only thing that does not change however is the position of the output value, which always comes at the beginning.\n",
"\n",
"Next, Let’s see examples of 7 different types of problems where you can use list comprehensions instead of for-loops."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example Type 1: Simple for-loop\n",
"\n",
"**Problem Statement**: Square each number in mylist and store the result as a list.\n",
"\n",
"The ‘For Loop’ iterates over each number, squares the number and appends to a list."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 4, 9, 16, 25]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"mylist = [1,2,3,4,5]\n",
"result = []\n",
"\n",
"for i in mylist:\n",
" result.append(i**2)\n",
"\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How to convert this to a list comprehension? Take the output in the same line as the for condition and enclose the whole thing in a pair of [ .. ]."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 4, 9, 16, 25]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension Version\n",
"[i**2 for i in [1,2,3,4,5]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example Type 2: for-loop with conditional filtering\n",
"\n",
"What if you have an if condition in the for loop? Say, you want to square only the even numbers:\n",
"\n",
"**Problem statement**: Square only the even numbers in mylist and store the result in a list."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[4, 16]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"mylist = [1,2,3,4,5]\n",
"result = []\n",
"\n",
"for i in mylist:\n",
" if i%2==0:\n",
" result.append(i**2)\n",
"\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In list comprehension, we add the ‘if condition’ after the for-loop if you want to filter the items."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[4, 16]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension Version\n",
"[i**2 for i in [1,2,3,4,5] if i%2==0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Example Type 3: for-loop with ‘if’ and ‘else’ condition\n",
"\n",
"Let’s see a case where you have an ‘if-else’ condition in the for-loop.\n",
"\n",
"\n",
"**Problem Statement**: In mylist, square the number if its even, else, cube it."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 4, 27, 16, 125]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"mylist = [1,2,3,4,5]\n",
"result = []\n",
"\n",
"for i in mylist:\n",
" if i%2==0:\n",
" result.append(i**2)\n",
" else:\n",
" result.append(i**3)\n",
"\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In previous example, we wanted to filter the even numbers. But in this case, there is no filtering. So put the if and else before the for-loop itself."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 4, 27, 16, 125]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension Version\n",
"[i**2 if i%2==0 else i**3 for i in [1,2,3,4,5]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example Type 4: Multiple for-loops\n",
"\n",
"Now let’s see a slightly complicated example that involves two For-Loops.\n",
"\n",
"**Problem Statement**: Flatten the matrix mat (a list of lists) keeping only the even numbers."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[2, 4, 6, 8, 10, 12, 14, 16]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"mat = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]\n",
"result = []\n",
"for row in mat:\n",
" for i in row:\n",
" if i%2 == 0:\n",
" result.append(i)\n",
"\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can you imagine what the equivalent list comprehension version would look like? It’s nearly the same as writing the lines of the for-loop one after the other."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[2, 4, 6, 8, 10, 12, 14, 16]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension version\n",
"[i for row in mat for i in row if i%2==0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Example Type 5: Paired outputs\n",
"\n",
"**Problem Statement**: For each number in list_b, get the number and its position in mylist as a list of tuples."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(6, 2), (4, 8), (6, 2), (1, 3), (2, 7), (2, 7)]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"mylist = [9, 3, 6, 1, 5, 0, 8, 2, 4, 7]\n",
"list_b = [6, 4, 6, 1, 2, 2]\n",
"\n",
"result = []\n",
"for i in list_b:\n",
" result.append((i, mylist.index(i)))\n",
"\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this case, the output has 2 items instead of one. So pair both of them as a tuple and place it before the for statement."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(6, 2), (4, 8), (6, 2), (1, 3), (2, 7), (2, 7)]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension version\n",
"[(i, mylist.index(i)) for i in list_b]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Example Type 6: Dictionary Comprehensions\n",
"\n",
"Same problem as previous example but output is a dictionary instead of a list of tuples.\n",
"\n",
"**Problem Statement**: For each number in list_b, get the number and its position in mylist as a dict."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{6: 2, 4: 8, 1: 3, 2: 7}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"mylist = [9, 3, 6, 1, 5, 0, 8, 2, 4, 7]\n",
"list_b = [6, 4, 6, 1, 2, 2]\n",
"\n",
"result = {}\n",
"for i in list_b:\n",
" result[i]=mylist.index(i)\n",
"\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To make a dictionary output, you just need to replace the square brackets with curly brackets. And use a : instead of a comma between the pairs."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{6: 2, 4: 8, 1: 3, 2: 7}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension version\n",
"{i: mylist.index(i) for i in list_b}\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example Type 7: Tokenizing sentences into list of words\n",
"\n",
"This is a slightly different way of applying list comprehension.\n",
"\n",
"**Problem Statement**: The goal is to tokenize the following 5 sentences into words, excluding the stop words."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"# Input:\n",
"sentences = [\"a new world record was set\", \n",
" \"in the holy city of ayodhya\", \n",
" \"on the eve of diwali on tuesday\", \n",
" \"with over three lakh diya or earthen lamps\", \n",
" \"lit up simultaneously on the banks of the sarayu river\"]\n",
"\n",
"stopwords = ['for', 'a', 'of', 'the', 'and', 'to', 'in', 'on', 'with']"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['new', 'world', 'record', 'was', 'set'],\n",
" ['holy', 'city', 'ayodhya'],\n",
" ['eve', 'diwali', 'tuesday'],\n",
" ['over', 'three', 'lakh', 'diya', 'or', 'earthen', 'lamps'],\n",
" ['lit', 'up', 'simultaneously', 'banks', 'sarayu', 'river']]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Loop Version\n",
"results = [] \n",
"for sentence in sentences:\n",
" sentence_tokens = []\n",
" for word in sentence.split(' '):\n",
" if word not in stopwords:\n",
" sentence_tokens.append(word)\n",
" results.append(sentence_tokens)\n",
"\n",
"results"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you wanted to flatten out the words in the sentences, then the solution would have been something like this:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['new', 'world', 'record', 'was', 'set', 'holy', 'city', 'ayodhya', 'eve', 'diwali', 'tuesday', 'over', 'three', 'lakh', 'diya', 'or', 'earthen', 'lamps', 'lit', 'up', 'simultaneously', 'banks', 'sarayu', 'river']\n"
]
}
],
"source": [
"print([word for sentence in sentences for word in sentence.split(' ') if word not in stopwords])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But we want to distinguish which words belong to which sentence, that is the original grouping of sentences should remain intact as a list.\n",
"\n",
"To achieve this, the entire second unit of for-loop, that is, the [word for word in sentence.split(' ') if word not in stopwords] part should be considered as an output and therefore will go at the beginning of the list comprehension."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['new', 'world', 'record', 'was', 'set'],\n",
" ['holy', 'city', 'ayodhya'],\n",
" ['eve', 'diwali', 'tuesday'],\n",
" ['over', 'three', 'lakh', 'diya', 'or', 'earthen', 'lamps'],\n",
" ['lit', 'up', 'simultaneously', 'banks', 'sarayu', 'river']]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List Comprehension Version\n",
"[[word for word in sentence.split() if word not in stopwords] for sentence in sentences]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 3. Practice Exercises (increasing level of difficulty)\n",
"\n",
"## Question 1. Given a 1D list, negate all elements which are between 3 and 8, using list comprehensions\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"# Input\n",
"mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n",
"\n",
"# Desired Output\n",
"# [1, 2, -3, -4, -5, -6, -7, -8, 9, 10]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, -3, -4, -5, -6, -7, -8, 9, 10]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[-i if 2 < i < 9 else i for i in mylist]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Question 2: Make a dictionary of the 26 english alphabets mapping each with the corresponding integer."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"# Desired output\n",
"# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6,\n",
"# 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12,\n",
"# 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18,\n",
"# 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24,\n",
"# 'y': 25, 'z': 26}"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}\n"
]
}
],
"source": [
"print({chr(i+97):i+1 for i in range(26)})"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}\n"
]
}
],
"source": [
"import string\n",
"print({string.ascii_lowercase[i]:i+1 for i in range(26)})"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}\n"
]
}
],
"source": [
"import string\n",
"print({a:i+1 for a,i in zip(string.ascii_lowercase, range(26))})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Question 3: Replace all alphabets in the string ‘Lee Quan Yew’, by substituting the alphabet with the corresponding numbers, like 1 for ‘a’, 2 for ‘b’ and so on."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"# Desired Output:\n",
"# [12, 5, 5, ' ', 17, 21, 1, 14, ' ', 25, 5, 23]"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[12, 5, 5, ' ', 17, 21, 1, 14, ' ', 25, 5, 23]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[ord(a.lower())-96 if a is not ' ' else ' ' for a in 'Lee Quan Yew']"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[12, 5, 5, ' ', 17, 21, 1, 14, ' ', 25, 5, 23]"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import string\n",
"d = {a:i+1 for a,i in zip(string.ascii_lowercase, range(26))}\n",
"[d.get(a.lower(), ' ') for a in 'Lee Quan Yew']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Question 4: Get the unique list of words from the following sentences, excluding any stopwords.\n",
"Hint: this is set comprehension"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"# Input\n",
"sentences = [\"The Hubble Space telescope has spotted\", \n",
" \"a formation of galaxies that resembles\", \n",
" \"a smiling face in the sky sky\"]\n",
"\n",
"stopwords = ['for', 'a', 'of', 'the', 'and', 'to', 'in', 'on', 'with']\n",
"\n",
"# Desired output:\n",
"# {'face', 'telescope', 'formation', 'smiling', 'hubble', 'spotted', \n",
"# 'resembles', 'has', 'sky', 'galaxies', 'that', 'space'}"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'galaxies', 'space', 'that', 'spotted', 'face', 'smiling', 'hubble', 'has', 'telescope', 'formation', 'resembles', 'sky'}\n"
]
}
],
"source": [
"print({word for sentence in sentences for word in sentence.lower().split() if word not in stopwords})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Question 5: Tokenize the following sentences excluding all stopwords and punctuations."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"# Input\n",
"sentences = [\"The Hubble Space telescope has spotted\", \n",
" \"a formation of galaxies that resembles\", \n",
" \"a smiling face in the sky\", \n",
" \"The image taken with the Wide Field Camera\", \n",
" \"shows a patch of space filled with galaxies\", \n",
" \"of all shapes, colours and sizes\"]\n",
"\n",
"stopwords = ['for', 'a', 'of', 'the', 'and', 'to', 'in', 'on', 'with']\n",
"\n",
"# Desired Output\n",
"# [['hubble', 'space', 'telescope', 'has', 'spotted'],\n",
"# ['formation', 'galaxies', 'that', 'resembles'],\n",
"# ['smiling', 'face', 'sky'],\n",
"# ['the', 'image', 'taken', 'wide', 'field', 'camera'],\n",
"# ['shows', 'patch', 'space', 'filled', 'galaxies'],\n",
"# ['all', 'shapes,', 'colours', 'sizes']]"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['hubble', 'space', 'telescope', 'has', 'spotted'],\n",
" ['formation', 'galaxies', 'that', 'resembles'],\n",
" ['smiling', 'face', 'sky'],\n",
" ['image', 'taken', 'wide', 'field', 'camera'],\n",
" ['shows', 'patch', 'space', 'filled', 'galaxies'],\n",
" ['all', 'shapes,', 'colours', 'sizes']]"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[[word for word in sentence.lower().split() if word not in stopwords] for sentence in sentences]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Question 6: Create a list of (word:id) pairs for all words in the following sentences, where id is the sentence index."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"# Input\n",
"sentences = [\"The Hubble Space telescope has spotted\", \n",
" \"a formation of galaxies that resembles\", \n",
" \"a smiling face in the sky\"]\n",
"\n",
"# Desired output:\n",
"# [('the', 0), ('hubble', 0), ('space', 0), ('telescope', 0), ('has', 0), ('spotted', 0),\n",
"# ('a', 1), ('formation', 1), ('of', 1), ('galaxies', 1), ('that', 1), ('resembles', 1),\n",
"# ('a', 2), ('smiling', 2), ('face', 2), ('in', 2), ('the', 2), ('sky', 2)]"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('the', 0), ('hubble', 0), ('space', 0), ('telescope', 0), ('has', 0), ('spotted', 0), ('a', 1), ('formation', 1), ('of', 1), ('galaxies', 1), ('that', 1), ('resembles', 1), ('a', 2), ('smiling', 2), ('face', 2), ('in', 2), ('the', 2), ('sky', 2)]\n"
]
}
],
"source": [
"print([(word, i) for i, sentence in enumerate(sentences) for word in sentence.lower().split()])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Question 7: Print the inner positions of the 64 squares in a chess board, replacing the boundary squares with the string ‘—-‘."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": [
"# Desired Output:\n",
"# [['----', '----', '----', '----', '----', '----', '----', '----'],\n",
"# ['----', (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), '----'],\n",
"# ['----', (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2), '----'],\n",
"# ['----', (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3), '----'],\n",
"# ['----', (1, 4), (2, 4), (3, 4), (4, 4), (5, 4), (6, 4), '----'],\n",
"# ['----', (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), '----'],\n",
"# ['----', (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), '----'],\n",
"# ['----', '----', '----', '----', '----', '----', '----', '----']]"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), '----'],\n",
" ['----', (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2), '----'],\n",
" ['----', (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3), '----'],\n",
" ['----', (1, 4), (2, 4), (3, 4), (4, 4), (5, 4), (6, 4), '----'],\n",
" ['----', (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), '----'],\n",
" ['----', (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----']]"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[['----' if any([k == v for k in (i,j) for v in (0,7)]) else (i, j) for i in range(8)] for j in range(8)]"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['----', (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', '----', '----', '----', '----', '----', '----', '----'],\n",
" ['----', (1, 7), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), '----']]"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[[(i,j) if not(i in (0, 7) or j not in (0, 7)) else ('----') for i in range(8)] for j in range(8)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.7.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@ybg345
Copy link

ybg345 commented Nov 10, 2019

Thanks for the notebook. I would like to create a same for myself unless I find it. Now it's time for me to practice and learn.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment