1

I have a list of things like this:

My_list = [['A1'],['B2'],['C3']]

I am asking the user to enter a LETTER (only) indicating which element to delete. So, for example, if the user entered 'B', the 2nd entry should be deleted and the list should look like this:

My_list = [['A1'],['C3']]

I have tried several solutions, but below is my best attempt at this...and i believe i'm not too far away from the final answer.

My_list = [['A1','B2','C3']]

print('What LETTER pairing would you like to delete?')
get_letter = input()
delete_letter = get_letter.upper()

for each_element in My_list:
    for each_pair in each_element:
        if each_pair[0] == delete_letter:
            location = My_list.index(each_pair)
            clues_list.pop(location)
            print('done')

when i run and enter 'B' the Compile error says...

ValueError: 'B2' is not in list

...but B2 is in list!

Where am i going wrong?

Tiny
  • 409
  • 2
  • 8
  • 20

2 Answers2

0

The error message is correct: 'B2' is not in My_list, although ['B2'] is!

You need to remove each_element, not each_pair, and should not do so while iterating over the list. For example, try:

location = None
for index, each_element in enumerate(My_list):
    for each_pair in each_element:
        if each_pair[0] == delete_letter:
            location = index
            break
if location is not None:
    My_list.pop(location)

However, it seems likely that a different data structure would be more useful to you, e.g. a dictionary:

data = {'A': 1, 'B': 2, 'C': 3}

where the code becomes as simple as:

if delete_letter in data: 
    del data[delete_letter]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

You can have it done in a much more concise way (using list comprehension):

My_list = [['A1','B2','C3']]

get_letter = raw_input('What LETTER pairing would you like to delete? ')
delete_letter = get_letter.upper()
print delete_letter
new_list = [var for var in My_list[0] if delete_letter not in var]
print new_list

A few caveats: not in will try to find delete_letter anywhere in the variable, so if you want it to have more exact matches you can look into .startswith. Then, my piece of code blindly follows your list of lists.

favoretti
  • 29,299
  • 4
  • 48
  • 61
  • what difference does raw_input have compared to input()? – Tiny May 09 '14 at 14:19
  • Answer is [here](http://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) :) Also contains answers about python 2. – favoretti May 09 '14 at 14:22
  • @user3396486: if you're using Python 3, (which your `print` syntax suggests), the chief difference is that `raw_input` will give you a NameError and the `print` here is a syntax error... – Wooble May 09 '14 at 15:05
  • (Calling `str()` on the results of `raw_input` is pointless... it always returns a `str` anyway.) – Wooble May 09 '14 at 15:06
  • Yeah, indeed, I was playing around with `input()`, forgot to remove. – favoretti May 09 '14 at 17:43