Nov-10-2019, 08:07 PM
Hello, hello.
I'm learning Python with a book(Python Crash Course), and at the part to code a game called 'Alien invasion'. To be more specific, currently I'm following to code bullets to be fired from a ship.
I have encountered this below.
"When you use a for loop with a list (or a group in Pygame), Python expects that the list will stay the same length as long as the loop is running. Because we can't remove items from a list or group within a for loop, we have to loop over a copy of the group. We use the copy() method to set up the for loop (line2), which enables us to modify bullets inside the loop."
I have 6 questions.
1 - why does Python like the length of a list to be the same within a for loop?
2 - is it common to keep the same length of list within for loop in programming languages?
3 - How does it possibly modify the original list by making a copy of it?????????!!!!!!!!!!!
4 - what about a while loop?
5 - what other solution is out there to modify a list within a for loop?
6 - is this sentence "it is not safe to modify the list during an iterative looping" the same as the sentence "Python expects that the list will stay the same length as long as the loop is running"?
Thank you in advance.
I'm learning Python with a book(Python Crash Course), and at the part to code a game called 'Alien invasion'. To be more specific, currently I'm following to code bullets to be fired from a ship.
I have encountered this below.
# Get rid of bullets that have disappeared. for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet)and, the author wrote,
"When you use a for loop with a list (or a group in Pygame), Python expects that the list will stay the same length as long as the loop is running. Because we can't remove items from a list or group within a for loop, we have to loop over a copy of the group. We use the copy() method to set up the for loop (line2), which enables us to modify bullets inside the loop."
I have 6 questions.
1 - why does Python like the length of a list to be the same within a for loop?
2 - is it common to keep the same length of list within for loop in programming languages?
3 - How does it possibly modify the original list by making a copy of it?????????!!!!!!!!!!!
4 - what about a while loop?
5 - what other solution is out there to modify a list within a for loop?
6 - is this sentence "it is not safe to modify the list during an iterative looping" the same as the sentence "Python expects that the list will stay the same length as long as the loop is running"?
Thank you in advance.