+ 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

5th Jan 2020, 2:45 AM
꧁àŒș Jenspi àŒ»ê§‚
꧁àŒș Jenspi àŒ»ê§‚ - avatar
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
5th Jan 2020, 9:08 AM
HonFu
HonFu - avatar
+ 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
5th Jan 2020, 10:41 AM
XXX
XXX - avatar
+ 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?
5th Jan 2020, 3:34 AM
Ivan
Ivan - avatar
+ 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.
6th Jan 2020, 6:51 PM
Tibor Santa
Tibor Santa - avatar
+ 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 :)
5th Jan 2020, 1:20 PM
Ag Codes
Ag Codes - avatar
+ 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
5th Jan 2020, 3:21 AM
꧁àŒș Jenspi àŒ»ê§‚
꧁àŒș Jenspi àŒ»ê§‚ - avatar
+ 1
I like simple examples such as: even_numbers= [x for x in range(100) if x % 2 == 0]
5th Jan 2020, 1:34 PM
grdr