NNorbert
NNorbert

Reputation: 35

Removing item from a list by a variable

Basicly im having problem with deleting an item from a list. I'd like to to do it by a variable , somehow like this :

my_list = ["cat","dog","duck","horse","snake"]
import random
animal=(random.choice(my_list))
new_list = []
new_list.append(my_list)
new_list.remove(animal)
print(new_list)

and i get this : ValueError : list.remove(x) : x not in list

What would you guys recommend me?

Upvotes: 1

Views: 748

Answers (2)

Tete
Tete

Reputation: 1

The above answer is adequate. However, I would point out that you can debug code another way, that being:

import pdb 

and invoking in your function:

pdb.set_trace()

This basically allows you to enter the debugger at the calling stack frame. I find it much more resourceful.

Upvotes: 0

ggorlen
ggorlen

Reputation: 56895

You've picked a random item from your list and then added the entire old list as a single element in your new list. This creates a two-dimensional list that does not contain any string values in the outermost list.

The best way to debug this is to print your list to see what it contains before applying the removal:

print(new_list) # => [['cat', 'dog', 'duck', 'horse', 'snake']]

Did you notice the extra [[]]? That's a nested list.

Likely, your intent was to copy the list (done here using the slice operator):

my_list = ["cat","dog","duck","horse","snake"]
import random
animal=(random.choice(my_list))
new_list = my_list[:]
new_list.remove(animal)
print(new_list)

Beyond this, it's good practice to include spaces, remove unnecessary parentheses and put imports at the top of files.

Lastly, remove is a linear operation that looks at potentially every element in the list to find the element you want to remove. This may seem silly, but when you begin working with lists of thousands or millions of items, it becomes a huge problem to walk the list unnecessarily.

Try using pop and random.randint to pick an index and remove it from the list in one stroke (you'll still incur a penalty for shifting list members around to fill in the gap; removing from the middle of a list isn't ideal):

import random

my_list = ["cat", "dog", "duck", "horse", "snake"]
new_list = my_list[:]
new_list.pop(random.randint(0, len(my_list) - 1))
print(new_list)

Upvotes: 1

Related Questions