0

I have been studying Python and trying to create a simple telephone book. However, I can't solve how to delete an item by using an index. Here is the code that doesn't work:

number = 1
while number < len(book):
    for x in book:
        print("{}) NAME: {}   NUMBER: {} ".format(number,x,book[x]))
        number = number + 1
delete = input("Insert the number you want to delete\n")
delete = int(delete)
book.pop(delete - 1)

This code can successfully list all of the contact information in the phone book, but I cannot find any way to delete the items. I think it'd be impractical to insert the name of the person whom you want to delete.

Is there any alternative that I can do? Thank you so much.

Samwise
  • 68,105
  • 3
  • 30
  • 44
Deniz Kaya
  • 27
  • 3
  • 4
    Does this answer your question? [How to remove an element from a list by index](https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index) – 12944qwerty May 30 '21 at 14:31
  • Maybe you can share some sample input data and output? And what is the result when you run the original code? – Daniel Hao May 30 '21 at 14:33
  • Please fix the indentation of the code in your post. – mkrieger1 May 30 '21 at 14:34
  • The code doesn't make sense with the output -- you output the values in the `book` dict (`book[x]`) as `NUMBER`, but `number` in the code is an unrelated counter that's enumerating the entries. Which one are you trying to have the user refer to the book as? Having some sample data for `book` would help a lot. – Samwise May 30 '21 at 15:10

2 Answers2

0

Asuming book is a list, you can delete elements

  • by index with del book[index]
  • by element reference with book.remove(delete)
Saritus
  • 918
  • 7
  • 15
0

If I understood correctly what you want to do:

book=[("NAME1",2313),("NAME2",65345313),("NAME3",1112313),("NAME4",151377)]
while book:
    for x in range(len(book)):
        print("{}) NAME: {}   NUMBER: {} ".format(x,book[x][0],book[x][1]))
    book.pop(int(input("Insert the number you want to delete:")))
user2952903
  • 365
  • 2
  • 10