Python List Del & Reconciliation [duplicate] - python

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I'm trying to delete multiple elements from a list.
The elements are having their indexes evaluated dynamically, and stored in a list called "dstry". It may look something like this:
arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2]
dstry = [1, 2, 9]
However, if I do...
for i in dstry:
del arr[i]
The list begins to shrink, and dstry's target elements are no longer where they should be.
Logically, how can I get around this? It'd be nice if the del could resolve all at once and delay the collapse of the array. Should I instead replace the elements with a flag value and then del them wherever they appear later so that index is not a factor?
Thanks

A bit creative solution, but this should fix the problem with the index you had.
arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2]
dstry = [1, 2, 9]
x=len(arr)
for i in dstry:
del arr[-x+i]
print(arr)

Related

I don't understand the difference between these codes [duplicate]

This question already has answers here:
Difference between del, remove, and pop on lists
(14 answers)
Closed 2 years ago.
data = [2, 4, 3, 1, 5, 10, 9]
data.pop()
print(data)
result: [2, 4, 3, 1, 5, 10]
the above is what i think makes sense
however,
data = [2, 4, 3, 1, 5, 10, 9]
Print(data.pop())
I got this
Result : 9
what is the difference?
In the 1st situation, you are printing a list of data. I have re-lined the code and added comments to make it more understandable:
Scenario 1:
data = [2, 4, 3, 1, 5, 10, 9] # the given data list
data.pop() # pop the last element off the list
print(data) # print 'data' (which is the list)
The reason why the result here is [2, 4, 3, 1, 5, 10] is because you are popping from the list, and then printing the list itself.
Scenario 2:
data = [2, 4, 3, 1, 5, 10, 9] # the given data list
print(data.pop()) # print the value returned by data.pop(), which is 9
# Result : 9
List.pop() is a method that returns the popped value from the list. So, by doing print(data.pop()), you are requesting to print the single popped value rather than the data list in its entirety.
See the Python documentation on the List.pop() method here.
The pop() method returns the value which was deleted from the list.
If you try to print that d.pop() it just returns the removed value.
When you use pop( ) it returns the last element of the list and internally it deletes last element from the list.
Note that in the first code you’re printing data ( the list ) and in the second one you’re printing what pop returns

Python - iterating over lists

I want my code's 2nd function to modify the new list made by my 1st function.
If I am understanding things correctly giving a list as an argument will give the original list (my_list in this case).
so the code removes 1 & 5 and then adds 6, but not 7?
my_list = [1, 2, 3, 4, 5]
def add_item_to_list(ordered_list):
# Appends new item to end of list which is the (last item + 1)
ordered_list.append(my_list[-1] + 1)
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
for items_to_remove in ordered_list:
ordered_list.remove(items_to_remove)
if __name__ == '__main__':
print(my_list)
add_item_to_list(my_list)
add_item_to_list(my_list)
add_item_to_list(my_list)
print(my_list)
remove_items_from_list(my_list, [1,5,6])
print(my_list)
output of
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 4, 6, 8]
instead of wanted
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 3, 4, 7, 8]
Thank you and sorry for the elementary question
In your remove_items_from_list function you are iterating through the wrong list. You should iterate through every item in the items_to_remove list like this:
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
for item in items_to_remove:
ordered_list.remove(item)
This will now iterate through each item in the remove list and remove it from you ordered_list.
There is a bug in the remove_items_from_list function. For it to achieve what you want it should go:
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
for item in items_to_remove:
ordered_list.remove(item)
As a side note, your code has incorrect number of blank lines before function definitions. Should be two blank lines before the function, and not more than one blank line inside functions. It seems not to have affected the code for now, but makes it harder to read, and could cause problems in future.
In the second function you want to iterate over items_to_remove (and not your original list) and then remove every item.
Use:
def remove_items_from_list(ordered_list, items_to_remove):
for item_to_remove in items_to_remove:
ordered_list.remove(item_to_remove)
And don't change the a list when you are iterating over it,which may cause bug.

Python: Theory as to why I can't Do: print(i.extend(j)) [duplicate]

This question already has answers here:
Why do these list methods (append, sort, extend, remove, clear, reverse) return None rather than the resulting list?
(6 answers)
Closed 6 years ago.
Python Theoretical Question
I'd like to learn theory behind why "print(i.extend(j))" DOESN'T work.
It's OUTPUT is: "None".
print(j) DOES work (It's OUTPUT is: "[4, 5, 6, 7, 8, 9]")
i = [1, 2, 3]
j = [4, 5, 6]
k = [7, 8, 9]
# I'd like to learn theory as to why following doesn't work
# OUTPUT is: "None"
print(i.extend(j))
# Following does work (OUTPUT is: "[1, 2, 3, 4, 5]")
j.extend(k)
print(j)
The answer is simple -
extend doesn't return anything, and any function that doesn't return a value is taken to have returned None.

Trim a list to a maximum number of elements [duplicate]

This question already has answers here:
How to force a list to a fixed size?
(7 answers)
Closed 3 years ago.
I would like to remove the oldest-added (i.e. the first) elements of a list, such that this list never exceeds 100 elements.
I thought about:
L = [327983, 232382, 1, 2, 3, 4, 5, 6, 23]
if len(L) > 100:
for i in range(len(L)-100):
del L[0]
print L # [4, 5, 6, 23]
Is there a solution without iteration (or more generally: a nicer solution) for trimming the beginning of the list, so that it has <= 100 elements?
Sidenote: Isn't there something else than lists, for this purpose? i.e. a data structure that has a maximum size, and such that if more data comes, the oldest are deleted! (It makes me think about FIFO? Stack? Pipe?)
How about using collection.deque? If you specify maxlen, it will not store more than maxlen elements.
>>> from collections import deque
>>> q = deque([1, 2, 3], maxlen=3)
>>> q
deque([1, 2, 3], maxlen=3)
>>> q.append(4)
>>> q
deque([2, 3, 4], maxlen=3)
You can just assign a slice back to your list
L = L[-100:]

Efficient way to get the position info of the biggest item in a Python list [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Pythonic way to find maximum value and its index in a list?
Say, in list [2, 3, 6, 9, 2, 3, 1, 5, 7], I want to get 3 (position of item 9) as output.
A similar question but for numpy array
My intuition is to build a tuple, and sort the tuple, and get the biggest item's position. I believe there are many better ways....
pos = mylist.index(max(mylist))
This includes all internal python logic - Therefore the best possible implementation.
Like this:
lst = [2, 3, 6, 9, 2, 3, 1, 5, 7]
maxval = max(lst)
maxpos = lst.index(maxval)

Categories