1

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?

2
  • 1
    You new_list has one element: my_list. Commented Mar 10, 2019 at 0:06
  • In other words, replace the line new_list.append(my_list) with new_list = list(my_list). That assigns a copy of my_list to the name new_list. Commented Mar 10, 2019 at 0:08

2 Answers 2

1

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.