my_list = [i for i in range(5)]
→ Creates: [0, 1, 2, 3, 4]
m = [my_list[i] for i in range(5) if my_list[i] % 2 != 0]
→ Filters out odd elements only:
my_list[0] = 0 → even → skipped
my_list[1] = 1 → odd → included
my_list[2] = 2 → even → skipped
my_list[3] = 3 → odd → included
my_list[4] = 4 → even → skipped
→ Result: [1, 3]
List Comprehension:
my_list = [i for i in range(5)]
This creates a list of integers from 0 to 4: [0, 1, 2, 3, 4].
Filtered List Comprehension:
m = [my_list[i] for i in range(5) if my_list[i] % 2 != 0]
This iterates over the indices 0 to 4 and includes my_list[i] in the new list m only if my_list[i] % 2 != 0 (i.e., the element is odd).
The odd elements in my_list are 1 and 3.
Output:
print(m) prints the list m, which contains the odd elements [1, 3]
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
Abbribas
1 month, 2 weeks agozwakenberg
6 months, 1 week ago