-2

My code is something like

aList = ['apple', 'banana', 'cherry'] 
anotherList = ['orange', 'apple', 'blueberry'] 
adifferentList = ['strawberry', 'pear', 'peach']
aSet = [aList, anotherList, adifferentList] 
for i in a set: 
     if i.index("apple"):
          temp = i.index("apple")
          del i[temp]
     else:
          pass

I was hoping that if a list doesn't contain "apple" it will just pass but it is currently erroring with that the list does not contain that value. Be gentle, I've taken a quarter of coding.

Edit: Error is as follows

ValueError: 'apple' is not in list

4
  • It would be great if you can provide more code and exact error message it shows you. Also docs might help to with examples. examples Commented Jun 27 at 23:52
  • I've updated the original post with additional details. Thank you Commented Jun 28 at 0:00
  • It is mighty confusing to use i for anything other than an index. Commented Jun 28 at 1:36
  • What should be the behaviour if a list contains more than one occurrence of "apple" Commented Jun 28 at 6:10

4 Answers 4

2

.index() will always raise a ValueError If the item is not found, it does not return None or -1

You can do it by following these points.

  1. Use in instead of index to avoid ValueError. It returns True or False

  2. Use remove() which is clearer and safer than index + del.

  3. No need for else: passIt’s redundant.

a_list = ['apple', 'banana', 'cherry']
another_list = ['orange', 'apple', 'blueberry']
different_list = ['strawberry', 'pear', 'peach']
all_lists = [a_list, another_list, different_list]

for sublist in all_lists:        # using `in` instead of `index`
    if "apple" in sublist:
        sublist.remove("apple")  # Safely removes 'apple' if it exists

print(all_lists)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much this is very helpful. I am using google colabs for this application and it seems if I don't include else pass that it will loop for an extra iteration for some reason. I appreciate the thorough and easy to follow response.
0

It looks like there might be a small typo in your loop, and you must have had there aSet instead of a set, please double-check that to avoid syntax errors.

Also, be careful with using .index() in a condition. Since .index() returns the position of the element (which can be 0), using it directly in an if statement can be tricky because 0 is considered False in Python. Instead, it’s safer to check if the element exists with the in operator first. examples of how .index() works

aList = ['apple', 'banana', 'cherry'] 
anotherList = ['orange', 'apple', 'blueberry'] 
adifferentList = ['strawberry', 'pear', 'peach']
aSet = [aList, anotherList, adifferentList]

for sublist in aSet:
    if "apple" in sublist:
        temp = sublist.index("apple")
        del sublist[temp]

And operator in - Returns True if a sequence with the specified value is present in the object

Comments

0

The way you approach this could depend on whether it's possible that "apple" occurs more than once in one of the sub-lists. If you want to remove any/all occurrences then you could do this:

all_lists = [
    ["apple", "banana", "cherry"],
    ["orange", "apple", "blueberry", "apple"],
    ["strawberry", "pear", "peach"],
]

for list_ in all_lists:
    list_[:] = [e for e in list_ if e != "apple"]

print(*all_lists, sep="\n")

Note that the 2nd sub-list has 2 occurrences of "apple". Thus, the output will be:

['banana', 'cherry']
['orange', 'blueberry']
['strawberry', 'pear', 'peach']

Comments

0

Here is an alternative solution using a list comprehension:

aList = ['apple', 'banana', 'cherry']
anotherList = ['orange', 'apple', 'blueberry', 'apple']
adifferentList = ['strawberry', 'pear', 'peach']
aSet = [aList, anotherList, adifferentList]

aSet = [[item for item in sublist if item != 'apple'] for sublist in aSet]
print(aSet)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.