 # Why does the code use less than 6 if it needs to stop at 6?

You are adding students to a Poetry class, the size of which is capped at 6.

while len(students_in_poetry) < 6:
student = all_students.pop()
students_in_poetry.append(student)

print(students_in_poetry)

There might be something I’m not seeing here, but if the class is capped at 6, why isn’t len(students_in_poetry)<=6? I tried it this way and it added a 7th student. I thought len(students_in_poetry)<6 would print 5 elements/students.

We go with less than since when there are 5 elements, the code is allowed to run once more. When we allow =6, then the code runs one more time after that, hence it reaches 7.

7 Likes

Understood. Thank you.

2 Likes

Because a list count from zero, not 1. In this example, 0 1 2 3 4 5 is six elements. A list with n length will have n elements with index from 0 to n-1.

Not exactly. The loop just repeats until there are already 6 elements in the list. For example, if there were 6 elements in the list (length of list = 6), it wouldn’t run the loop anymore since if it did it would become length = 7.

This is not a correct explanation.
We go less than six because this while loop is a first check-then perform. The last iteration will be when length to be equals to 5, at the end of the iteration length will be 6. At while loop will check again, the condition will not be met, and the loop ends.

2 Likes

When we are entering the While loop our len equals to zero and we add one student to the list. Then we go on the second round of the While loop and the len of poetry class is now one student – we add another student.
So we start with the zero len of the list and that’s why when our len is 5 we enter the while loop for the last time and at the end of this last time we are adding the 6th student.
We add a student after we check the len of the list.