Skip to main content

Python List Comprehension

Way to create a new list from iterable by transforming the items.

Syntax:


[ output_expression for item in iterable [ conditions ] ]

numbers = [1, 2, 3, 4, 5, 6]
squares = [number**2 for number in numbers]
print(squares)
#Output: [1, 4, 9, 16, 25, 36]

Using if condition


We can use if condition to filter out some elements.

numbers = [1, 2, 3, 4, 5, 6]
squares = [number**2 for number in numbers if number > 2]
print(squares)
#Output: [9, 16, 25, 36]

Using multiple if condition (ANDing)

We can use multiple if conditions to filter out elements. All if conditions will be ANDed

numbers = [1, 2, 3, 4, 5, 18, 30]
list_1 = [number for number in numbers
          if number % 2 == 0
          if number % 3 == 0]
print(list_1)
#Output: [18, 30]

Using ‘in’ statement (ORing)


'in' keyword can be used to create a condition statement.

numbers = [1, 2, 3, 4, 5, 18, 30]
list_2 = [number for number in numbers
          if number % 3 in (1, 2)]
print(list_2)
#Output: [1, 2, 4, 5]

Using if condition in output expression



If condition can be used to alter the resulting list.

numbers = [1, 2, 3, 4, 5]
list_3 = ["Even" if number % 2 == 0
          else "Odd" for number in numbers]
print(list_3)
#Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']

Using the if-else statement


Ladder of if-else statement can be used to alter the resulting list.

numbers = [25, 35, 50, 90]
list_4 = ["First" if number >= 60
          else "Second" if 45 <= number < 60
          else "Third" if 33 <= number < 45
          else "Failed"
          for number in numbers]
print(list_4)
# Output: ['Failed', 'Third', 'Second', 'First']

Nesting list comprehension


Nesting of list comprehension is just like the nested for loops.

list_6 = [[n for n in range(1, 4)] for number in range(3)]
print(list_6)
# Output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Dictionary comprehension


Dictionary comprehension works the same as lists. The difference is that we will work on (key, value) pairs.

dict_1 = {'a': 1, 'b': 3, 'c': 4}
dict_2 = {key: value**2 for key, value in dict_1.items()}
print(dict_2)
# Output: {'a': 2, 'b': 6, 'c': 8}

Set comprehension


Set can be created just like the list is comprehended.

numbers = [1, 2, 3, 4, 5]
set_1 = {number*2 for number in numbers}
print(set_1)
# Output: {2, 4, 6, 8, 10}

If you have some cool tricks regarding this topic, feel free to comment below. Thanks.

Comments

Popular posts from this blog

Prefix to Infix Conversion

With a given Prefix Expression, we will see how to convert Prefix Expression into Infix Expression using stack.   Algorithm to convert Prefix Expression to Infix Expression: In this algorithm, we will use stack to store operands during the conversion. The step are as follows: Read the prefix string While the end of prefix string scanned from right to left symb = the current character If symb is an operator poped_sym1 = pop the stack poped_sym2 = pop the stack concat the string  STR = ( poped_sym1 )+ ( operator )+( poped_sym2 ) push the string STR into stack Else push the operand symb into stack End If End While infix_str = pop the stack   Function to convert Prefix Expression to Infix Expression: void prefix_to_infix(char prefix[], char infix[]){ char op[2]; //operator string char poped1[MAX]; char poped2[MAX]; char temp[MAX]; int i = strlen(prefix); op[1] = '\0'; while(--i != -1){ if(prefix[i] == ' '){ continue; } if(isoper...

Concatenating two link list

Here we will see how to concat two single link list into other link list. First we copy the content of first list in third list and then the content of second list into third list. Algorithm for concatenation of two link list: This algorithm will use three list. List 1 and List 2 will be concatenated into List 3. The step below: Copy the list 1 into list 3 Copy the list 2 at the last of list 3 Function to concat two link list: void concatLists(NODE **start1, NODE **start2, NODE **mergeinto){ NODE *temp; temp = *start1; while(temp != NULL){ insertAtLast(&*mergeinto, temp->info); temp = temp->next; } temp = *start2; while(temp != NULL){ insertAtLast(&*mergeinto, temp->info); temp = temp->next; } }   Program to concat two link lists: #include <stdio.h> #include <malloc.h> struct node{ int info; struct node *next; }; typedef struct node NODE; void insertAtLast(NODE **, int); void traverse(NODE **); void concatLists(NODE **,...

Implementation of Stack to store different data types

Here we will see how to implement stack using structure and union to store different datatypes in stack. First we define the basic structure for elements/items to be stored in the stack. struct Items{ int ele_type; union { int ivalue; float fvalue; char *strvalue; } stack_element; }; In the above code, we have defined a Items structure to store the info about the type of items in ele_type variable and a union variable named stack_element to store the actual value of stack items. In union the, ivalue is used to store the integer value, fvalue to store floating value and strvalue to store the string value. If you wish to add other datatype, you can add any datatype within the union. Now we will define the structure to implement the stack. The code below: struct Stack{ int top; struct Items element[MAX]; }; In the above code, struct Stack is defined to hold the top of stack and the array of Items structure named element to hold the actual Items defined above. MA...