Reputation: 53
I have an array, a=[1,2,3,4,5,6,7], and I am trying to find the index of all the values which are less than 6 and greater than 2, using list comprehension. I am using the following technique:
tk = [b if (a[b]>=2 & [b]<=6) for b in range(len(a))]
It keeps saying that there is a syntax error at 'for'. Any idea how to resolve this? Or what am I doing wrong?
Upvotes: 0
Views: 329
Reputation: 114230
The placement of the condition in a comprehension has always been a point of much confusion to me as well, so I came up with a working mnemonic device.
If you are excluding elements from the list, if
belongs to the loop, and goes after the for
:
[item for item in items if condition]
If you are deciding between values, that's just a normal ternary operator, which appears as part of the comprehension before the for
:
[item1 if condition else item2 for item1, item2 in items]
Your case is clearly the first one since you are excluding elements. The test should therefore go after the for
, with appropriate syntax fixes:
tk = [b for b in range(len(a)) if (2 <= a[b] <= 6)]
It might be more intuitive to implement the same operation using enumerate
to get the indices instead of range
:
tk = [item for index, item in enumerate(a) if 2 <= index <= 6]
Upvotes: 0
Reputation: 356
Below code will work
tk = [b for b in range(len(a)) if (a[b]>= 2 and a[b] <= 6)]
tk
[1, 2, 3, 4, 5]
I have modified 3 things here:
Hope this will help
Upvotes: 2
Reputation: 3698
This should be enough to do the trick:
>>> indices = [i for i, x in enumerate(a) if 2 < x < 6]
>>> indices
[2, 3, 4]
Upvotes: 3