For loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

For loop

I was thinking... Is there a way too delete all the element in a list with for loop🤔🧐? And not just deleting it... Somthing like this... A = [1,2,3,4,5] for i in A: How can delete it all the elements now.. Is it even possible

8th Jun 2019, 8:21 AM
Amirabbas
Amirabbas - avatar
5 Answers
+ 1
Yes, it's possible, just a little long-winded and tricky. The problem is as you loop through your list and delete elements from it, you change where the loop is iterating on. What I mean is this: if your list is lst = [1,2,3,4], if you loop on that list using for i in lst, the first iteration is on the first element (1 in this case), then the second iteration is on the second element. But, as you've deleted your first element (1), the second element is now 3, so 3 is the next element that would get deleted. So if you tried it, you would end up with lst = [2,4]. The trick is to loop backwards over the list. That way, it doesn't interfere with the order that the loop iterates over the list. The other thing you need is the index() method. This returns the index of the element that you pass to the method. So, if lst = [1,2,3,4,5], lst.index(3) returns 2. So now you can hopefully see that if you do: lst = [1,2,3,4,5] for i in lst[::-1]: del(lst[lst.index(i)]) print(lst) #[] you can delete all the elements in your list.
8th Jun 2019, 9:03 AM
Russ
Russ - avatar
+ 2
Actually, you're right. remove() is much easier. remove() deletes the element that you pass, whereas del would require you to specify the index that you need to delete, as would pop(). lst = [1,2,3,4,5] for i in lst[::-1]: lst.remove(i) print(lst) #[]
8th Jun 2019, 9:12 AM
Russ
Russ - avatar
+ 1
lst = [...] for i in range(len(lst)): del(lst[0])
8th Jun 2019, 8:31 AM
Russ
Russ - avatar
0
Yeah that is true Russ... I actually said it wrong... How to delete them when we say ut like this Lst = [1,2,3,4,5] for i in Lst: What should we say after... To delete all the elements.. Is it even possible
8th Jun 2019, 8:48 AM
Amirabbas
Amirabbas - avatar
0
Thanks Russ... Is there a deference between del and remove?
8th Jun 2019, 9:05 AM
Amirabbas
Amirabbas - avatar