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

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.

Related

Remove duplicate of a list via list matching in Python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Removing duplicates in lists
(56 answers)
Closed 7 days ago.
I have chosen a slightly different procedure to remove duplicates of a list. I want to keep a new list in parallel, in which each duplicate is added. Afterwards I check if the element is present in the "newly created list" in order to delete it.
The code looks like this:
# nums = [1,1,2] or [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums
for i in nums:
if nums[i] not in t:
t.append(nums[i])
else:
nums_new.remove(nums[i])
nums = nums_new
print(nums)
For the case when nums = [1,1,2] this works fine and returns [1,2].
However, for nums = [0,0,1,1,1,2,2,3,3,4] this case does not seem to work as I get the following output: [0, 1, 2, 2, 3, 3, 4].
Why is this? Can someone explain me the steps?
There are two issues with your code:
Since you are iterating over a list, for i in nums, i is your actual number, not the indexer, so you should just use i instead of nums[i].
nums_new = nums will not actually make a copy of nums, but instead it will make a second binding to the very same list. So you should write nums_new = nums.copy() to avoid changing your original list while you iterate over it.
With those two changes your code works as you wish:
nums = [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums.copy()
for i in nums:
if i not in t:
t.append(i)
else:
nums_new.remove(i)
nums = nums_new
print(nums)
Returns [0,1,2,3,4].
Of course this is an academic exercise of some kind, but note that the Pythonic way to remove duplicates from a list is:
list(dict.fromkeys(nums)) if you want to preserve the order, and
list(set(nums)) for a slightly faster method if you do not care about order.

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]))

Understanding a specific for loop in Python [duplicate]

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.

Why doesn`t list[:][0] get me the first row of the list? [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 6 years ago.
For the following:
list=[[2, 3, 5], [7, 8, 9]]
Why does [list[0][0], list[1][0]] represent the first row ([2, 7]), but the command list[:][0] or list[0:2][0] returns the first column ([2, 3, 5])?
The way I see it list[:][0] should get all the possible values for the first parameter (that is 0 and 1) and 0 for the second, meaning it would return the first row. Instead what it does is return the first column and I can't understand why.
In python, the [a:b:c] syntax creates a new list. That is,
list = [1,2,3]
print(list[:])
is going to print a list, not a value.
Therefore, when you say list[:][0] you are making a copy of the original list (list[:]) and then accessing item 0 within it.
Of course you know, item 0 of the original list (list[0]) is another list.
I think you want:
[sl[0] for sl in list]
Elaboration:
This is called a "comprehension." It is a compact special syntax for generating lists, dicts, and tuples by processing or filtering other iterables. Basically {..}, [..], and (..) with an expression inside involving a for and optionally an if. Naturally, you can have multiples (like [x for x in y for y in z]) of the for, and multiples of the if.
In your case, it's pretty obvious you want a list. So []. You want to make the list by taking the first item from each sublist. So [sl[0] for sl in list].
Here's a more-detailed article: http://carlgroner.me/Python/2011/11/09/An-Introduction-to-List-Comprehensions-in-Python.html

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