1. List Compression
List compression is used as one liners in python they are sometimes very useful While we doesn't want to write a loop to fill list
For example : if we want to create a list of square of odd numbers from pre-existing list of numbers 1 to 10
We consider doing this in two ways :
l1=[1,2,3,4,5,6,7,8,9,10]
result=[]
for item in l1:
if item%2 != 0:
result.append(item**2)
print(result)
l=[x**2 for x in range(10) if x%2!=0]
print(l)
Result For Both :
[1,9,25,49,81]
Let's see how it works
l=[result loop condition]
• The first one is result that you want
• The second one is loop it's on you how you use it
• The third one is if else condition that you want to follow (optional)
Note : This also works with dictionaries ,tuples
Let's move on to second one
2. any , all keywords
any ,all keyword return a boolean they are generally used when we need to check multiple condition
For example : if we have a list of string and we need to check whether all the words are present in given string
We generally use two ways :
- Check condition one by one
Comments
Post a Comment