+ 1

What's the difference here ?

names = ["Vishal", "Saras", "Sandeep"] for name in names: if len(name) > 6: names.append(name) print(names) #This goes as infinite loop #But if in for loop I use slicing [:] , then it works #properly

16th Jun 2019, 7:54 AM
Vishal Khushalani
Vishal Khushalani - avatar
6 Answers
+ 5
When you do for name in names[:]: you iterate over all items of a copy of the list. So the list you take the items from is a different list than the one you append new elements to and there won't be an infinite loop
16th Jun 2019, 8:14 AM
Anna
Anna - avatar
+ 4
You're not really slicing the list. list[:] is one way to copy the list so that changes that are made to the original list won't affect the copied list (and vice versa). Try this: l = [1, 2, 3] a = l b = l[:] Here, "a" will just be another label for "l". Whatever you do to "a", affects "l" too and vice versa. Whereas b won't be affected by any changes you make to "l" (or "a"): a.append(4) print(l) # [1, 2, 3, 4] <<== changing a changed l l.append(5) print(a) # [1, 2, 3, 4, 5] <<== changing l changed a print(b) # [1, 2, 3] <<== b is independent from both l and a because of [:]
16th Jun 2019, 8:31 AM
Anna
Anna - avatar
+ 3
Sandeep has more than 6 letters, so you append it to "names". Then you take the next item from "names", which is the name Sandeep that you just added, find out that it has more than 6 letters, append it to "names" and you're in an infinite loop
16th Jun 2019, 8:09 AM
Anna
Anna - avatar
+ 2
Yeah ! Understood 😊😊 Tysm
16th Jun 2019, 8:34 AM
Vishal Khushalani
Vishal Khushalani - avatar
+ 1
But when I use slicing [ : ], how it works properly then ?
16th Jun 2019, 8:12 AM
Vishal Khushalani
Vishal Khushalani - avatar
+ 1
You mean when we slice the list, iteration goes over new list and we don't care about original list,whatever may happen to it ? Is this what exactly happens ?
16th Jun 2019, 8:17 AM
Vishal Khushalani
Vishal Khushalani - avatar