I'm currently learning Python, and I struggle to understand what the slicing [:] does in the for loop shown below.
I failed to find any questions about the [:]
syntax, so I am posting a question.
I understand that writing namesList[2:]
would slice the list from index 2: ['three', 'four', 'five']
And namesList[:2]
would slice the list until index 1: ['one', 'two']
.
- If in the for loop I only put
for nm in namesList:
it is stuck on an infinite loop, constantly inserting 'four' to index 0. Why is it stuck? - From what I can see in debugging, in the for loop with
namesList[:]
, it continues from where it stopped. But whynamesList:
doesn't continue, andnamesList[:]
does? How does[:]
work, what does the syntax mean?
names = "one two three four five"
namesList = names.split()
for nm in namesList[:]:
if nm[0] == "f":
namesList.insert(0, nm)
print(namesList)
# Output:
['five', 'four', 'one', 'two', 'three', 'four', 'five']
names = "one two three four five"
namesList = names.split()
for nm in namesList:
if nm[0] == "f":
namesList.insert(0, nm)
print(namesList)
# Infinite loop