Python Forum
List Comparisons and Deleting Valuebles - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: List Comparisons and Deleting Valuebles (/thread-10115.html)



List Comparisons and Deleting Valuebles - KaleBosRatjes - May-13-2018

So i have 2 lists. when the value in list_a is not between 75 and 400 it has to remove the value in the list_a and list_b in the same place. I dont know why it gives this strange output? I hope you guys can help :)

#input
list_a = [50,100,200,500,50]
list_b = [1,2,3,4,5]

#code
for i,j in zip(list_a,list_b):
    if 75<i<400:
        list_a.remove(i)
        list_b.remove(j)
print(list_a,list_b)

#output 
[50, 200, 500, 50] [1, 3, 4, 5]

#prefered output
[100,200] [2,3]



RE: List Comparisons and Deleting Valuebles - j.crater - May-13-2018

list.remove takes as argument the value you want to remove, not the index. What you are probably looking for is del (delete). For this purpose list.pop is also commonly used, but in your case it won't make much difference.


RE: List Comparisons and Deleting Valuebles - KaleBosRatjes - May-13-2018

But when I change the code to the del function, it gives an error: "list assignment index out of range"

list_a = [50,100,200,500,50]
list_b = [1,2,3,4,5]

#code
for i,j in zip(list_a,list_b):
    if 75<i<400:
        del list_a[i]
        del list_b[j]
print(list_a,list_b)

#IndexError: list assignment index out of range



RE: List Comparisons and Deleting Valuebles - j.crater - May-13-2018

The code will require a bit of modification. Note that indices in Python start with 0, and items in your list_b start with 1. And of course, deleting element with index "i" will be no good. Examine the code a bit, you will quickly figure why.


RE: List Comparisons and Deleting Valuebles - volcano63 - May-13-2018

Your initial code did not work because you were removing the first occurence of i - instead of the one at position matching j (one-letter variables should be a punishable offence Doh )

(May-13-2018, 01:27 PM)KaleBosRatjes Wrote: But when I change the code to the del function, it gives an error: "list assignment index out of range"

list_a = [50,100,200,500,50]
list_b = [1,2,3,4,5]

#code
for i,j in zip(list_a,list_b):
    if 75<i<400:
        del list_a[i]
        del list_b[j]
print(list_a,list_b)

#IndexError: list assignment index out of range

Your i and j are list elements and you try to use them as list indices.

Regardless, deleting from lists is heavy and inefficient operation - O(n), building new lists is usually more efficient.

list_a = [50,100,200,500,50]
list_b = [1,2,3,4,5]

combined = [[key, val] for key, val in zip(list_a, list_b) if 75 < key < 400]
print(list(zip(*combined)))
And the result is - tada!:
Output:
[(100, 200), (2, 3)]
PS Please, read PEP-8