Reputation: 24665
a = [1,2,3,4]
for loop in range(0,len(a)):
if a[loop]%2==0:
a.remove(a[loop])
loop = loop - 1
I want to reduce the list by filtering numbers which can be divided by 2. There are two questions here:
loop
is not reduced by one as expected in R
, how can I make it working?Thanks for the prompt reply, first part of the question is solved, but what about the second part? What if I want to use for-loop to deal with it and make the loop
to be reduced by ` if the condition of 'dividable by two' is fulfilled?
Upvotes: 1
Views: 1083
Reputation: 2304
I found this question looking for an algorithm to do what the question says: "loop with 'reducing list'". However, it looks like all the answers are for implementing a filter, which is what OP really wanted. For anyone really interested in a reducing list:
def make_filter(comp_val):
return lambda x: not (x.startswith(comp_val) and x != comp_val)
i = 0
l = list_1.copy()
while i < len(l):
s_3 = list(filter(make_filter(s_3[0]), s_3))
i += 1
The point of doing this would be to reduce timespace (O) and compute on many iterations through a list.
Upvotes: 0
Reputation: 239453
If you want to remove all the elements from the list, if it is not divisible by 2, then the best way is to create a new list without the numbers not divisible by 2, like this
[item for item in a if item % 2 != 0]
You can also use the filter
function, like this
filter(lambda item: item % 2 != 0, a)
If you are using Python 3.x, then you need to generate the list of items from the filter
object using list
function, like this
list(filter(lambda item: item % 2 != 0, a))
Apart from these methods, if you want to do in-place replacement, then you might want to do it in reverse, like this
a = [1,2,3,4]
for loop in range(len(a) - 1, -1, -1):
if a[loop] % 2 == 0:
a.remove(a[loop])
Note: Whenever possible, prefer list comprehension method.
Upvotes: 2
Reputation: 11717
A list comprehension can do the trick:
# Define data in variable a
a = [1,2,3,4]
# Apply the list comprehension to filter list a
a = [i for i in a if i%2==0]
Upvotes: 0