6

Is there an easy way to delete an entry in a list? I would like to only remove the first entry. In every forum that I have looked at, the only way that I can delete one entry is with the list.remove() function. This would be perfect, but I can only delete the entry if I know it's name.

    list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
    list.remove(0)

This doesn't work because you can only remove an entry based on it's name. I would have to run list.remove('hey'). I can't do this in this particular instance.

If you require any additional information, ask.

AlG
  • 14,697
  • 4
  • 41
  • 54
  • 4
    Just use `list.pop(0)` – C.B. Oct 30 '15 at 19:03
  • Are you just removing the first entry? `.pop()` would it for you. Or do you need to remove a random single entry in the list e.g. could be [0] or [3], etc.? – AlG Oct 30 '15 at 19:04
  • `list.remove(list.index('hey'))` – David Zemens Oct 30 '15 at 19:09
  • Even if you could only remove an item by its contents, you know its contents: it's `list[0]`. So if you wanted to remove the first item using `remove` it'd be `list.remove(list[0])`. But don't do it that way, use `pop()` or `del`. – kindall Oct 30 '15 at 19:10

4 Answers4

7

These are methods you can try:

>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> del my_list[0]
>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> if 'hey' in my_list:     # you're looking for this one I think
...     del my_list[my_list.index('hey')]
... 
>>> my_list
['hi', 'hello', 'phil', 'zed', 'alpha']

You can also use filter:

 my_list = filter(lambda x: x!='hey', my_list)

Using list comprehension:

my_list = [ x for x in my_list if x!='hey']
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
2

First of all, never call something "list" since it clobbers the built-in type 'list'. Second of all, here is your answer:

>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> del my_list[1]
>>> my_list
['hey', 'hello', 'phil', 'zed', 'alpha']
RobertB
  • 1,879
  • 10
  • 17
1

Lists work with positions, not keys (or names, whatever you want to call them).

If you need named access to your data structure consider using a dictionary instead which allows access to its value by using keys which map to the values.

d = {'hey':0, 'hi':0, 'hello':0, 'phil':0, 'zed':0, 'alpha':0}

del d['hey']

print(d)  # d = {'alpha': 0, 'hello': 0, 'hi': 0, 'phil': 0, 'zed': 0}

Otherwise you will need to resort to index based deletion by getting the index of the element and calling del alist[index].

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

To add to the poll of answers..how about:

>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> my_list=my_list[1:]
>>> my_list
['hi', 'hello', 'phil', 'zed', 'alpha']
flamenco
  • 2,702
  • 5
  • 30
  • 46