+ 25
[solved] How to use for loop and if statement in one line??
For example: for i in range(10): if i % 2 == 0: i += 1 else: i -= 1 I can make if and else statements in one line but I don't know how to add for loop too in the line... PLEASE HELP🙏🙏
32 Answers
+ 18
print( [((i+100,i)[i%2],i-100)[i>=5] for i in range(10)])
+ 16
Here is a one-liner, that creates the same result as your code:
print([i+1 if i % 2 == 0 else i - 1 for i in range(10)])
+ 14
as function
for i in range(10):
i += (-1) **((i+1)%2)
I
+ 9
This simple but powerful tutorial by HonFu changed the way I see for loops. Do check it out and go through it.
https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
+ 5
+ 5
a=[i+1 if i%2==0 else i-1 for i in range(10)]
print (a)
For loop and if else statements written in one line using list comprehension methods
+ 4
RKK Thank you so much🙏... But I was not asking for that
+ 4
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 Yesss👏👏👏
+ 3
Hell yeah list comprehensions, as well as dictionary and generator ones
+ 3
Kiibo Ghayal oll
+ 3
X = [i += 1 for i in range(10) if i%2 == 0 else i -= 1]
print(x)
+ 2
RKK Thank you so much
But still I am unable to assign values
+ 2
Thank you so much 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥, now I am able to make it... Without any error
Louis thank you for your concern but I am not able to understand your code as there are no if conditions
+ 2
for i in range(10):i += 1 if i %2==0 else -1
+ 2
Use list comprehensions or lambda functions
+ 2
print([i+1 if i % 2 == 0 else i - 1 for i in range(10)])
+ 2
Please message me personally
+ 2
List = input(':')
If any([i == $ for i in list]):
Print('True')
+ 2
you can use it when you iterate in lists we use a for-statement to declare our intentions. But did you know that it is possible to add a condition to this? This will add only those items to the list that meet the condition (for which the condition is True).
For example
[i for i in range(8) if i%2!=0]
Ans: [1, 3, 5, 7]
and also you can nested conditionals. With a Python list comprehension, it doesn’t have to be a single condition; you can nest conditions. Here’s an example.
[i for i in range(8) if i%2==0 if i%3==0]
Ans: [0, 6]
+ 1
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 But I am not able to assign values by using this method