I wanted to delete words from a list having length greater than 3. I used del (item) but it didn't worked. Here is the code:
lst=['XDA-OT','hi','loc','yeah']
for i in lst:
if len(i)>3:
del i
And the output:
lst
['XDA-OT', 'hi', 'loc', 'yeah']
Now I used remove() from Python List functions and I got the desired result.
Here is the code for the same:
lst=['XDA-OT','hi','loc','yeah']
for i in lst:
if len(i)>3:
lst.remove(i)
OUTPUT:
print(lst)
['hi', 'loc']
Also I have doubt regarding usage of index of list to delete a element from list but didn't understand how to frame the question.
I get IndexError whenever I delete a element using index. CODE:
lst=['XDA-OT','hi','loc','yeah']
for i in range(len(lst)):
if len(lst[i])>3:
del lst[i]
OUTPUT ERROR:
IndexError
<ipython-input-35-617282928840> in <module>()
1 for i in range(len(lst)):
----> 2 if len(lst[i])>3:
3 del lst[i]
IndexError: list index out of range
Same using remove() function. CODE:
lst=['XDA-OT','hi','loc','yeah']
for i in range(len(lst)):
if len(lst[i])>3:
lst.remove(lst[i])
OUTPUT ERROR:
IndexError
<ipython-input-39-1d824ca5b061> in <module>()
1 for i in range(len(lst)):
----> 2 if len(lst[i])>3:
3 lst.remove(lst[i])
IndexError: list index out of range
del iis just deleting the variablei. That doesn't affect your list.lstusing.copyor using slice[:]and iterate over and remove if fromlstif some condition is met.