Last active
January 8, 2018 11:37
-
-
Save MishraKhushbu/a9a1452707975cbf17db1706c7ae61f7 to your computer and use it in GitHub Desktop.
List Comprehension 6 dec 2017
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Basic Examples: | |
1.{ x^2: x is a natural number less than 10 } | |
[x*2 for x in range(0,10)] | |
2.{ x: x is a whole number less than 20, x is even } | |
[x for x in range(0,20) if x%2 == 0] | |
3.{ x: x is an alphabet in word ‘MATHEMATICS’, x is a vowel } | |
[x for x in "MATHEMATICS" x not in "AEIOU"] | |
======================================================================================= | |
The same gets implemented in a simple LC construct in a single line as: | |
[ output_expression() for(set of values to iterate) if(conditional filtering) ] | |
====================================================================================== | |
Things to keep in mind: | |
LC will always return a result, whether you use the result or nor. | |
The iteration and conditional expressions can be nested with multiple instances. | |
Even the overall LC can be nested inside another LC. | |
Multiple variables can be iterated and manipulated at same time. | |
====================================================================================== | |
Example 3: Dictionary Comprehension | |
Aim: Take two list of same length as input and return a dictionary with one as keys and other as values. | |
{list1[i] : list2[i] for i in range(len(list1))} | |
Output {'a1': 2, 'a0': 1, 'a3': 3} | |
========================================================================================== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment