Python - List Comprehension
Tags: python, tutorial, programming, beginners
Published: 2020-01-07 07:36:34

List comprehension is a technique of creating new lists using other iterable and in fewer lines of codes. The iterable object which can be used in this technique can be any data structure like list, tuple, set, string and dictionary, etc. An iterable created by using range() function can also be used here.

The syntax used in list comprehension generally contains three segments:
<ul>
<li><strong>iterable: </strong>iterable object like list, tuple, set, string, dictionary, etc.</li>
<li><strong>transformation function: </strong>a transformation function that needs to be applied to the iterable.</li>
<li><strong>filters: </strong>filters/conditions which are required to apply on iterable.</li>
</ul>

<h2>Syntax</h2>
<pre >
#list comprehension syntax
list = [tranform_func(i) for i in iterable if filters]

#which is equivalent to...
for i in iterator:
  if filters:
    list.append(tranform_func(i))
</pre>

<h3>Example: List comprehension using various iterable</h3>
Below example describes how to apply different transformation functions on a given iterable.	
<pre>
#creating list of squares of natural numbers
MyRange = range(1,6)
NewList = [i*i for i in MyRange]
print(NewList)

#creating list of odd numbers
MyTuple = (1, 2, 3, 4, 5, 6, 7, 8)
NewList = [i for i in MyTuple if i%2!=0]
print(NewList)

#creating list of characters (in uppercase) of a string 
MyString = 'Hello'
NewList = [i.upper() for i in MyString]
print(NewList)
</pre>


<h3>Output</h3>	
<pre>
[1, 4, 9, 16, 25]

[1, 3, 5, 7]

['H', 'E', 'L', 'L', 'O']
</pre>


<h2>List Comprehension and transformation function</h2>
<p>In above examples, transformation function is defined inside the list comprehension syntax. Alternatively, it can be defined outside of it, which gives the user to create more innovative function.</p>
<h3>Example: Create Grades using List Comprehension</h3>
<p>In below example, a function called <i>grade()</i> is created which is used inside list comprehension syntax to categorize iterator's element.</p>
  
<pre>
def grade(x):
  if x &lt; 0:
    return 'Invalid'
  elif x &gt;= 0  and x &lt; 30:
    return 'Fail'
  elif x &gt;= 30  and x &lt; 50:
    return 'Grade C'
  elif x &gt;= 50  and x &lt; 75:
    return 'Grade B'
  elif x &gt;= 75  and x &lt;= 100:
    return 'Grade A'
  else:
    return 'Invalid'

MyList = [20, 45, 67, 90, -1, 89, 102]
NewList = [grade(i) for i in MyList]
print(NewList)
</pre>

<h3>Output</h3>    
<pre>
['Fail', 'Grade C', 'Grade B', 'Grade A', 'Invalid', 'Grade A', 'Invalid']
</pre>

<h3>Example: Find Prime Numbers using List Comprehension</h3>
<p>A function called <i>prime</i> is created which is further applied on iterator using list comprehension technique to find out prime elements of the iterator. Please see the example below for more details.</p>
   
<pre>
def prime(x):
  i = 2
  if x &gt;= 2: 
    count = 0 
  else: 
    count = None
  while i &lt;= x-1:
    if x%i==0:
      count = 1
      break;
    i = i + 1
  if count == 0:
    return x

MyRange = range(1,20)
NewList = [prime(i) for i in MyRange if prime(i) is not None]
print(NewList)
</pre>

<h3>Output</h3>   
<pre>
[2, 3, 5, 7, 11, 13, 17, 19]
</pre>


<h3>References</h3>
<ul>
  <li><a href="https://en.wikipedia.org/wiki/List_comprehension">Wikipedia: List Comprehension</a></li>
  <li><a href="https://docs.python.org/3/tutorial/datastructures.html#tut-listcomps">Python.org: List Comprehension</a></li>
  <li><a href="https://www.datacamp.com/community/tutorials/python-list-comprehension">DataCamp: List Comprehension</a></li>
  <li><a href="https://www.alphacodingskills.com/python/pages/python-list-comprehension.php">AlphaCodingSkills: List Comprehension</a></li>
  <li><a href="https://www.youtube.com/watch?v=1HlyKKiGg-4">YouTube: List Comprehension</a></li>
</ul>