Skip to main content

Using if-else statements in List Comprehension

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). Click Here to see more about list comprehension. 

In this post, we will see how to use if - else statements in list comprehension. 

Let's have a quick look at using if statement alone before we see if - else statements. 

E.g.: 

Create a list of odd numbers less than 10. 

odd_numbers = [number for number in range(10) if number % 2 != 0]

    In the above example, We are using if statement towards the end for identifying the odd numbers. 

    We are only considering the odd numbers using the if statement and leaving the others. But if we have to to a different operation for even numbers and different operation for odd numbers, we should be using if-else statements. 

    if-else statements in List Comprehension

    So, How do we use else statement in list comprehension? Is it just adding else statement after if condition? 

    Syntax wise it's a little different if we need to use both if and else statements. 

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

    E.g.: 

    Create a list with square of even numbers between 0 and 9 and just add "ODD" for every odd number between 0 and 9.

    This requires both if and else statements.

    result_list = 
    [number * number if number % 2 == 0 else "ODD" for number in range(10)]

    Let's breakdown the above statement into four parts. 
    • number * number indicates the expression that needs to be run if the condition is true and the resulting value is to be added to the list. This can be any expression as per the requirement. 
    • if number % 2 == 0 indicates the required if condition.
    • else "ODD" contains both the else statement and the value that needs to be added if the condition mentioned is False. Value here can be any expression as required. For example, We can use number * number if we need to calculate the square of odd number.
    • for number in range(10) indicates the for loop over an iterable. 

    So, syntax wise if - else statements in list comprehension would look like below.

    [expression if condition else expression for element in iterable]

    Key difference between using is if and if-else is the placement of these statements.
    • if statement is to be used at the end (i.e., after for) if no else statement is required. 
    • if - else statements are to be used at the beginning (i.e., before for) if else statement is required. 

    One thing to note is, List comprehension looks to be the easiest way of creating list. But, this can get more complicated and difficult to read and understand when we use it with multiple if (and else) and for statements. 



    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