Skip to main content

List Comprehension in Python

List Comprehension

List comprehension is one of the ways of creating list. List would be created as a result of some operation on a range, set or list based on some condition (optional). 

This makes the list creation easier to code and easy to understand. 

Let's have a look at an example to understand this better. 

E.g.: 

Create a list with the list of odd numbers less than 10. 

We will first see how to create a list with out list comprehension. 

Create a list with odd numbers

In the above example we are doing in four steps. 
  • Line - 1: Create an empty list by using square brackets. 
  • Line - 2: for loop on a range of numbers till 10. 
  • Line - 3: if condition to check if the number is an odd number. 
  • Line - 4: add the odd number to the list using append() method. 
Same can be done in a single statement with list comprehension. 

List comprehension in Python

We have embedded for loop and if condition inside the square brackets directly to create a list with odd numbers. 

let's break this statement and see in detail. 

odd_numbers = [number for number in range(10) if number % 2 != 0]
  • square brackets [] to create the list. Similarly {} and () can be used as well to create dictionary, set or generator. We will see more about set and dictionary comprehensions towards the end.
  • number highlighted in green indicate the value to be added to the list. This can include some arithmetic operation as well, we will see an example by using some operation.
  • for number in range(10) to loop through the range from 0 to 9. Any iterable can be used in place of range). 
  • if number % 2 != 0 condition to identify the odd number. 

Let's have a look at another example to create a list with squares of odd numbers less than 10. 

List comprehension in Python

We have replaced number with 'number * number' to calculate the square of an odd number and add to the list. This can be any expression based on the requirement. 

We have looked at creating a list by using one iterable. We can use multiple iterables at the same time to create a list (or nested lists). 

Let's have a look at the example by using two lists. 

E.g.: 

Create a list with the product of each element in a list with the elements of another list. 

List comprehension with two lists in Python

In the above example, 
  • We are using one list (even_numbers) and one tuple (odd_numbers). 
  • Two for loops to fetch each element in the list.
    • 'for even in even_numbers' would be considered as the first for loop and for every even number in the list second loop would be repeated. 
    • 'for odd in odd_numbers' would loop through odd_numbers for every element from the first loop.
  • For each combination operation 'even * odd' is calculated and added to the list. 
This is same as using nested for loops with out using list comprehension. 

Nested for loops in Python

Both these examples would return the same list [2, 6, 10, 4, 12, 20, 6, 18, 30]. 

Similarly, we can create nested list (or matrices) using the same instead of creating product. 

Nested lists using List comprehension in Python

We can also use the list comprehension to convert nested lists to a single list (matrix flattening). 

Matrix flattening in Python

In the above example, 
  • First for loop is repeated on the matrix.
  • For every list from the matrix, second for loop is repeated and returns the element.
  • element returned is added to the list created. 

List comprehension is very useful to create the lists, at the same time we need to be aware of not over using it (like using it on more number of lists). This would make this difficult to understand and maintain the code. 

One thing to remember is it becomes extremely difficult to debug when they are not working as expected, specially when we are using multiple lists.

So, it is best to decide whether to use list comprehension or not based on the functionality rather than to using it all the time.

Let's have a look at Set comprehension and Dictionary comprehension with simple examples. 

Set comprehension

Set comprehension is same as list comprehension, only difference is we use curly brackets {} instead of square brackets. Using round brackets () would create a generator not tuple, we will see more about generators in different post. 

Set comprehension in Python

Dictionary comprehension

Dictionary comprehensions are also similar to set comprehensions. Only difference is it requires the key to be added. 

Let's have a look at an example. 

Dictionary comprehension in Python

In the above example, we are considering the number in the range as a key and square of the number as corresponding value. 

We can also use dictionary with the list of keys supplied from a list. 

Dictionary comprehension in Python

In the above example, 
  • We are creating a list with the keys required to be in the dictionary. 
  • Using List comprehension to get the squares of odd numbers in the range of 10. 
  • Dictionary comprehension to loop through the list of keys and assign the output of list comprehension as a value to the key. 

Hope the above was a bit of help to understand the List comprehension in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i