+ 4
Practicing list comprehensions
How did you practice list comprehensions? I want to understand them better, but I donât see any opportunity to use them enough to learn them
8 Answers
+ 4
You only learn something by doing it.
How about taking all practice codes of you and translating every for loop to comprehension?
https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
+ 4
ê§àŒșJennyàŒ»ê§ I was in the same position as you a little while back. But the best answer is practise and only practise. Try to use list comprehensions everywhere you can. Start from just small things like -
l1 = '1 2 3 4'.split()
l2 = [int(num) for num in l1]
- to making oneliners
print("The even numbers from the input are", *[int(i) for i in input().split() if not int(i)%2])
Well explained HonFu
+ 3
I use these in almost all the code coach solutions. its super convinient.
list_name = [ element for element in range(x) if condition]
Not the same but I also like squeezing conditions in my print statements:
print( âHelloâ if condition else âGoodByeâ)
Could you explain what part of thw syntax confuses you?
+ 3
My advice, look for opportunities where you can change your code to more pythonic.
Whenever you need to write a for loop, think again because it is very likely that it could also be written as a comprehension (even at the cost of defining an extra function, that you can use in an if condition).
Review your older codes and I am sure you will find plenty of cases where this is applicable.
Also keep in mind you can also do set and dict comprehension, and even generator expressions that look almost the same but have round brackets.
+ 2
I practiced it by first solving some task, and when I was finished I tried to decrease the lines of code I wrote by changing some things. This included changing simple for loops that changed or created a list by doing list comprehensions instead. Trying to decrease the amount of written code lines is a great way to learn new things :)
+ 1
Alexandr yep, are they just not used that often? ive only found one time to use one over the past 4 or so months
+ 1
I like simple examples such as:
even_numbers= [x for x in range(100) if x % 2 == 0]