Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Im learning python on Codecademy and this task prints the list from the last index to 6. Why doesn't it prints from the first index to 6?

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)

the output is: ['Loki', 'Arius', 'Obie', 'Alexa', 'Minerva', 'Dora']


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
355 views
Welcome To Ask or Share your Answers For Others

1 Answer

It has to do with

student = all_students.pop()

the last element will be removed from the list and assigned to student

But you can use pop(0) to get the first element, so your code becomes

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(0) # this pops out the first element
  students_in_poetry.append(student)

print(students_in_poetry)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...