Why doest this Loop syntax work and this Loop syntax doesn't when using .pop() ? HELP!

codecademy.com/paths/data-science/tracks/dspath-python-lists-and-loops/modules/dspath-loops/lessons/learn-python-loops/exercises/while

*Why does this code syntax work for using .pop() *

all_students = ["Alex", "Briana", "Cheri", "Daniele", "Dora", "Minerva", "Alexa", "Obie", "Arius", "Loki"]

students_in_poetry = []

while len(students_in_poetry) < 6:

  student = all_students.pop()

  students_in_poetry.append(student)
  
print(students_in_poetry)

BUT this one doesn’t??..

all_students = ["Alex", "Briana", "Cheri", "Daniele", "Dora", "Minerva", "Alexa", "Obie", "Arius", "Loki"]

students_in_poetry = []

while len(students_in_poetry) < 6:

   students_in_poetry = all_students.pop()

print(students_in_poetry)

because here:

students_in_poetry = all_students.pop()

.pop() will return an element (string) from the list

but because you don’t use append here, the list will now be overwritten be a string:

students_in_poetry = all_students.pop()
print(students_in_poetry)

so now, we don’t determine if there are 6 students in class. We determine if we have some who has a name longer then 6 characters (and if there aren’t any, you have an infinity loop)

3 Likes