1

I want to know how to append all the items that weren't removed into a new list.

challenge = [1, 0, 9, 8, 5, 4, 1, 9, 3, 2, 3, 5, 6, 9]

def remove_values(thelist, value):
    newlist = []
    while value in thelist:
        thelist.remove(value)
        newlist.append()

bye = remove_values(challenge, max(challenge))

For example, if I remove all the 9s (the max), how do I append the rest into a new list?

fonfonx
  • 1,475
  • 21
  • 30
kissland
  • 23
  • 5
  • 1
    `return [x for x in thelist if x != value]` ? Or is there a deeper reason to mutate `thelist`? – timgeb May 09 '17 at 12:51
  • try with a for loop – Matt May 09 '17 at 12:52
  • If you must mutate the original list, you could do `for idx,item in enumerate(thelist): if item == value: newlist.append(thelist.pop(idx))`, the `pop()` call is O(n) though each time – Chris_Rands May 09 '17 at 12:55

1 Answers1

0
challenge = [1, 0, 9, 8, 5, 4, 1, 9, 3, 2, 3, 5, 6, 9]

# This will append every item to a new List where the value not is max
# You won't need 2 lists to achieve what you want, it can be done with a simple list comprehension
removed_list = [x for x in challenge if x != max(challenge)]
print(removed_list)
# will print [1, 0, 8, 5, 4, 1, 3, 2, 3, 5, 6]
Ludisposed
  • 1,709
  • 4
  • 18
  • 38