lst=[1,2,3,'b',4,5,6,'c','b',4,5,6,2,'c',9,0,1]
def delElement(E1,E2):
global end
for i,ele in enumerate(lst):
if ele==E1:
start=i
break
elif ele== E2:
end=i
break
del lst[start:end+1]
return(lst)
delElement('b','c')
-
You didn't define end? – Banana Aug 24 '20 at 18:16
-
`end` wont be defined as long as your `elif` is executed – Delrius Euphoria Aug 24 '20 at 18:17
-
3If you don't hit that line in an elif block, end is never assigned. When you hit an `E1`, you break out of your loop, so you never hit an `E2` – khelwood Aug 24 '20 at 18:17
2 Answers
Even though you have defined that you want to use the global variable end
on line 4, this variable does not have any value yet.
Since your for loop breaks after finding the value b
in your list, the value end will never be set. Instead, only the value of the variable start
will be set, since the first if-statement will evaluate to True first.
After the loop you are trying to delete a range of list items by referencing the variable end
, however, since this has not been given a value yet, it will throw an error.
A solution could be to also set the end
variable in the first if-statement, depending on your needs. Also, if possible, I would suggest avoiding using global variables like this, as explained in this Stack Overflow post.

- 21
- 2
in your current code, at the moment your for loop detects E1, it breaks and go right away to del lst[start:end+1]
without defining end. No sure what you want to achieve but keeping the same structure of code, just remove the first break:
def delElement(e1, e2):
for i, ele in enumerate(lst):
if ele == e1:
start = i
elif ele == e2:
end = i
break
del lst[start:end + 1]
return lst
lst = [1, 2, 3, 'b', 4, 5, 6, 'c', 'b', 4, 5, 6, 2, 'c', 9, 0, 1]
delElement('b', 'c')
I can see many potential error on the results depending of what you want to achieve exactly. Don't hesitate to add details for better answer...
EDIT: An ugly way but workable if your expected result is [1, 2, 3, 9, 0, 1]
:
def delElement(elementA, elementB, lst):
new_lst = []
feed_new_lst = True # New list is fed when this is true
for element in lst:
if element == elementA:
feed_new_lst = False # Stop feeding the new list
continue
if feed_new_lst:
new_lst.append(element)
if element == elementB:
feed_new_lst = True # Continue do feed the new list
return new_lst
lst = [1, 2, 3, 'b', 4, 5, 6, 'c', 'b', 4, 5, 6, 2, 'c', 9, 0, 1]
lst2 = ['b', 2, 3, 'c', 4, 'b', 6, 'c', 4, 5, 6, 'b', 9, 0, 'c']
print(delElement('b', 'c', lst))
# [1, 2, 3, 9, 0, 1]
print(delElement('b', 'c', lst2))
# [4, 4, 5, 6]

- 26
- 2
-
-
so your expected result (based on your list) would be `[1, 2, 3, 9, 0, 1]` ? – rblais Aug 25 '20 at 03:22