Understanding a specific for loop in Python [duplicate] - python

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 5 years ago.
A = [2,4,6,8,10,12]
for a in A:
if a%2 == 0: # If 2 divides a, remove a from A
A.remove(a)
print(A)
When I execute this block of code, the console output is [4,8,12].
My understanding of this code is that if any of the elements in [A] are divisible by 2, then we remove them from the list. In the list above, all elements are in fact divisible by 2, but only 2, 6, and 10 were removed. Anyone care to explain why 4, 8, and 12 were not removed?

Removing elements from a list while you're iterating through it messes up the iteration. You should use the filter function or a list comprehension instead.

Related

How do I create a remove every other element function? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 months ago.
I have written a script
def remove_every_other(my_list):
# Your code here!
rem = False
for i in my_list:
if rem:
my_list.remove(i)
rem = not rem
return my_list
It removes every other element from the list.
I input [1,2,3,4,5,6,7,8,9,10] it returns [1,3,4,6,7,9,10]
Which to me is very strange also if I input [Yes,No,Yes,No,Yes]
it outputs [Yes,No,Yes,No]
I have tried to figure it out for hours but couldn't get it to work, I am a beginner.
You could just use slicing for that. Or do you want to do it explicitly in a loop? For an explanation of the syntax, you can follow the link. Basically you take the full list (no start or end defined) with a step-value of 2 (every other element). As others have pointed out, you run into problems if you're modifying a list that you're iterating over, thus the unexpected behavior.
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
output_list = input_list[::2]
print(output_list)
This returns a copy of the list with every other element removed:
[1, 3, 5, 7, 9]
Since .remove() is being called upon the same list that you're iterating over, the order is getting disarranged.
We could append the items that you want at the end in another list to maintain the ordering in the original list.
def remove_every_other(my_list):
morphed_list = []
rem = True
for i in my_list:
if rem:
morphed_list.append(i)
rem = not rem
return morphed_list
In general, it is not a good idea to modify the list you're iterating over. You could read more about it over here: https://stackoverflow.com/questions/10812272/modifying-a-list-while-iterating-over-it-why-not#:~:text=The%20reason%20to%20why%20you,list%20of%20just%20odd%20numbers.

For loop is not executing as expected, sequence matters so can't use set() here [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I used a for loop to remove the duplicates in a list from the left side. For example, [3,4,4,3,6,3] should be [4,6,3]. And also the sequence cannot be changed, that's why I cannot use a set here. If I use set() here, the result would be [3,4,6].
def solve(arr):
for i in arr:
if i in arr[arr.index(i)+1:]:
arr.remove(i)
return arr
solve([1,2,1,2,1,2,3])
It should return [1,2,3]. Instead, I got [2,1,2,3]. I viewed the visualized execution of the code, and it seems when python got to the item '2' the second time, meaning when the arr is mutated to be [2,1,2,3], it just suddenly stopped iteration from the for loop and returned the list as it is. When it should detect there is still another '2' in the list. Please help
You can use set for this:
a = [1,2,1,2,1,2,3]
b = set(a)
Then b will be:
{1,2,3}
You can try this way:
def solve(arr):
another_arr = []
for i in arr:
if i in another_arr:
another_arr.remove(i)
another_arr.append(i)
else:
another_arr.append(i)
return another_arr
print(solve([1, 2, 1, 2, 1, 2, 3]))

How to get sum of all elements of given list using list comprehension? [duplicate]

This question already has answers here:
How to emulate sum() using a list comprehension?
(10 answers)
Closed 4 years ago.
l = [5, 7, 8, 2, 1, 4]
sum = 0
for i in l:
sum += i
print(sum)
how can I get sum of all elements but using list comprehension?
list comprehension should be used only for generating a list. You can simply use sum(l).
List comprehension always produces another list so I am not sure if you can even do that. You will surely need other function to fold the sequence into a single value.

Lists : printing number only if its not a duplicate [duplicate]

This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 8 years ago.
Given a list of n numbers how can i print each element except the duplicates?
d = [1,2,3,4,1,2,5,6,7,4]
For example from this list i want to print : 1,2,3,4,5,6,7
Since order doesn't matter, you can simply do:
>>> print list(set(d))
[1, 2, 3, 4, 5, 6, 7]
It would be helpful to read about sets
If the order does not matter:
print set(d)
If the type matters (want a list?)
print list(set(d))
If the order matters:
def unique(d):
d0 = set()
for i in d:
if not i in d0:
yield i
d0.add(i)
print unique(d)
All you have to do is
create an array.
get list's element.
if element exists in array, leave it.
and if it does not exists, print it.

Can I append items to a list that I am looping through in Python? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python: Adding element to list while iterating
This doesn't seem to work, but I am not sure why:
for n in poss:
poss.append(n+6)
Is there some rule that says I can't append items to a list that I am currently looping through?
Appending to the list while iterating through it will enter an infinite loop, since you are adding more elements to the loop in each iteration.
You should iterate on a copy of the list instead. For example, try the following:
for n in tuple(poss):
poss.append(n+6)
Your code actually works, but never ends because poss is continously growing.
Try:
poss = [1,2]
for n in poss:
poss.append(n+6)
if n > 10:
print poss
break
produces:
[1, 2, 7, 8, 13, 14, 19]

Categories

Resources