0

Python beginner just wondering why is it you're not able to pop() an item from a list by using it's value within a list, instead having to know it's index?

e.g.

colours = ["blue", "purple"]
colour_1 = colours.pop(0)
print(colour_1)

Why could I not instead write

colour_1 = colours.pop("blue")

Maybe a dumb question, but I was curious about this and I'm pretty new, thanks :)

  • You are looking for `list.remove` – juanpa.arrivillaga Dec 16 '20 at 14:23
  • Because pop() takes an index (position) as its argument. – L. Scott Johnson Dec 16 '20 at 14:24
  • 1
    It should be obvious that a single list method can't handle both remove-by-position and remove-by-value - how would it know which to do, in cases where the value is also a valid position number? – jasonharper Dec 16 '20 at 14:25
  • Well, @jasonharper gave you the answer, but if you only want to use ```pop()``` method, you can delete element by value like ```colour_1 = colours.pop(colours.index("blue"))``` – Sajid Dec 16 '20 at 14:31
  • It wasn't obvious to me why you wouldn't be able to write it as, for example. ' pop(0) ' for removing by index and something like ' pop("blue") ' for removing by value, the quotation marks being the differentiation between it knowing if you were searching by index or by value @jasonharper – Luke Gorman Dec 16 '20 at 17:25
  • Thanks @Sajid and I know about the remove() method which you can use to remove by value, but you can't also store the deleted value into a variable like you can with pop() can you? – Luke Gorman Dec 16 '20 at 17:27

0 Answers0