1

I'm doing a computing course and i have to do python. I'm stuck on a certain question. It says this

" Write a program that asks the user to type in 10 items for a list. The user is then asked for the index of the item that needs to be deleted The item is then deleted from the list. The list needs to be printed before and after the deletion takes place."

This is the only code I have so far

letters = ["a","b","c","d","e","f","g","h","i","j"]
print (letters)
del letters input()[]
print (letters)
Oneki
  • 45
  • 5
  • 2
    Looks like you need to spend some time with the [official Python tutorial](https://docs.python.org/3.4/tutorial/index.html). – TigerhawkT3 Jul 14 '15 at 08:28
  • 1
    Most of possible solutions are covered in the tutorial https://docs.python.org/3/tutorial/datastructures.html#more-on-lists – vaultah Jul 14 '15 at 08:29
  • possible duplicate of [How to remove an element from a list by index in Python?](http://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index-in-python) – Ankur Ankan Jul 14 '15 at 08:43

2 Answers2

2

You almost have it right. You should have a read of the docs

del letters[int(input())]

You just need to put input() inside the brackets.

user3636636
  • 2,409
  • 2
  • 16
  • 31
1

There are following steps:

Get input from the User. Use raw_input() to get values.

Note use input() for Python 3.x

e.g.

>>> nos_items = 10
>>> input_list = []
>>> while nos_items>0:
...     input_list.append(raw_input("Enter Item in the input List: "))
...     nos_items -= 1
... 
Enter Item in the input List: a
Enter Item in the input List: b
Enter Item in the input List: c
Enter Item in the input List: d
Enter Item in the input List: e
Enter Item in the input List: f
Enter Item in the input List: g
Enter Item in the input List: h
Enter Item in the input List: i
Enter Item in the input List: j
>>> input_list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Get delete index number from the user. Index start from 0. Do type casting to convert string to int e.g.

>>> del_index = int(raw_input("Enter delete item index:"))
Enter delete item index:3
>>> del_index
3
>>> 

Use pop() to delete item from the list.

e.g.

>>> input_list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> input_list.pop(del_index)
'd'
>>> input_list
['a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j']

Handle exception for boundary.

>>> imput_list.pop(33)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range


>>> try: imput_list.pop(33)
... except IndexError:
...     print "Index out of range."
... 
Index out of range.
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56