List comprehension means using for loop to create a list :
L = [i*2 for i in range(1,5)] #5 not included print(L) Output: [2,4,6,8]
We can use 2 for loops to get the words in a paragraph :
paragraph = ["This is sentence one." , 'This is sentence two.'] result = [word for sentence in paragraph for word in sentence.split()] print(result) Output: ['This', 'is', 'sentence', 'one', 'This', 'is', 'sentence', 'two']
We can use 2 for loops and an if to get words beginning with certain letters :
(the example below is using the paragraph defined above)
letters = ['s','o'] result = [word for sentence in paragraph for word in sentence.split() if word[0].lower() in letters] print(result) Output: ['sentence', 'one.', 'sentence']
We can use an if with any conditions we like :
numbers = [100,200,300,400] result = [n for n in numbers if n > 200] print(result) Output: [300,400]
We can make a list using double for in i and j format like this:
product_list = [ i*j for i in range(1,3) for j in range(10,20,5) ] #3 and 20 are not included print(product_list) Output: [10, 15, 20, 30]
We can make a dictionary too using for :
result = {i:i*3 for i in range(1,7,2)} print(result) Output: {1: 3, 3: 9, 5: 15}
We can use for to access the key in a dictionary.
In this example I try to get the best Hogwart pupils in a dictionary (highest remarks):
Hogwarts = {1:['Harry',80] , 2:['Ron',70], 3:['Hermione',90], 4:['Neville',60], 5:['Seamus',50]} best_pupils = {key:value[0] for key,value in students_data.items() if value[1] >= 70} print(best_pupils) Output: {1: 'Harry', 2: 'Ron', 3: 'Hermione'}
Various examples of creating lists and dictionary using for :
#times 2 if i is divisible by 3, otherwise plus 2 result = [i*2 if i%3==0 else i+2 for i in range(1,7)] print(result) Output: [3, 4, 6, 6, 7, 12] #create a dictionary containing cube numbers from 1 to 4 n = 4 result = {i:i**3 for i in range(1,n+1)} print(result) Output: {1: 1, 2: 8, 3: 27, 4: 64} #A list containing combinations of letters from 2 words result = [i+j for i in "po" for j in "he"] print(result) Output: ['ph', 'pe', 'oh', 'oe'] #Create a dictionary from a word. The key is in upper case, the value is double letter. result = {x.upper(): x*2 for x in 'potter'} print(result) Output: {'P': 'pp', 'O': 'oo', 'T': 'tt', 'E': 'ee', 'R': 'rr'}
Leave a Reply