-1
nums = [0,1,2,2,3,0,4,2]

val = 2

for i in nums:
    if i == val:
        nums.remove(i)
    else:
         continue
print(nums)

Result is [0,1,3,0,4,2] instead of [0,1,3,0,4]

maxmiljan
  • 9
  • 3

4 Answers4

0

Well maybe I am a little bit confused because in the title you ask for removing just the last item but in the question you ask for an expected result. I just took your code and make it work to get the expected output with a list comprehension. It looks like this:

nums_new = [i for i in nums if i != val]

You can ofcourse name nums_new to only nums.

Pixelbog
  • 236
  • 1
  • 8
0

Your mistake becomes clear if you print your data inside the loop:

nums = [0,1,2,2,3,0,4,2]

val = 2

for i in nums:
    if i == val:
        nums.remove(i)
    print(i, nums)
print(nums)

Output:

0 [0, 1, 2, 2, 3, 0, 4, 2]
1 [0, 1, 2, 2, 3, 0, 4, 2]
2 [0, 1, 2, 3, 0, 4, 2]
3 [0, 1, 2, 3, 0, 4, 2]
0 [0, 1, 2, 3, 0, 4, 2]
4 [0, 1, 2, 3, 0, 4, 2]
2 [0, 1, 3, 0, 4, 2]
[0, 1, 3, 0, 4, 2]

Note:

  • i goes through 0, 1, 2, 3, ..., i.e., not two 2s in a row. That's because you remove the first 2, but "the loop" doesn't care, it still goes to the next position in the list, which then holds the value 3.
  • You do find the 2 at the end, but since remove removes the first occurrence, it removes the earlier 2.
no comment
  • 6,381
  • 4
  • 12
  • 30
-1

You have a few options:

Filter

your_list = [1, 2, 3, 4, 2, 3, 4, 2]
filtered_values = filter(lambda value: value != 2, your_list)

The first argument is the filtering function, the second is your values - whatever evaluates to False is removed from the list.

List comprehension

your_list = [1, 2, 3, 4, 2, 3, 4, 2]
filtered_values = [value for value in your_list if value != 2]

There are many other ways of doing it, although those are the most common ways of doing it.

Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34
-3

You can also do this with the NumPy module:

import numpy as np
# generate 20 random integers between 0 (inclusive) and 5 (exclusive)
myarr = np.random.randint(0, 5, 20) 
print(myarr)
[0 2 0 1 2 0 3 0 0 0 3 4 1 3 1 4 1 0 4 4]
val = 2
myarr = np.delete(myarr, np.where(myarr == val))
print(myarr)
[0 0 1 0 3 0 0 0 3 4 1 3 1 4 1 0 4 4]
myarr = np.delete(myarr, np.where(myarr == val))

In that line we do the following: from the array myarr, delete the elements whenever that element equals val.

The same can be achieved with your initial list, by first converting it to a numpy array:

nums = np.array(nums)
scientist
  • 137
  • 6