Question: Write a loop that traverses the previous list and prints the length of
ID: 3619696 • Letter: Q
Question
Question: Write a loop that traverses the previous list and prints the length of each element. What happens if you send an integer to len?-
The reading for this question is below.
---
List Length
The function len returns the length of a list. It is a good idea to use this value as
the upper bound of a loop instead of a constant. That way, if the size of the list
changes, you won’t have to go through the program changing all the loops; they
will work correctly for any size list:
horsemen = ["war", "famine", "pestilence", "death"]
i = 0
while i < len(horsemen):
print horsemen[i]
i = i + 1
The last time the body of the loop is executed, i is len(horsemen) - 1, which is
the index of the last element. When i is equal to len(horsemen), the condition
fails and the body is not executed, which is a good thing, because len(horsemen)
is not a legal index.
Although a list can contain another list, the nested list still counts as a single
element. The length of this list is four:
[’spam!’, 1, [’Brie’, ’Roquefort’, ’Pol le Veq’], [1, 2, 3]] Question: Write a loop that traverses the previous list and prints the length of each element. What happens if you send an integer to len?
-
The reading for this question is below.
---
List Length
The function len returns the length of a list. It is a good idea to use this value as
the upper bound of a loop instead of a constant. That way, if the size of the list
changes, you won’t have to go through the program changing all the loops; they
will work correctly for any size list:
horsemen = ["war", "famine", "pestilence", "death"]
i = 0
while i < len(horsemen):
print horsemen[i]
i = i + 1
The last time the body of the loop is executed, i is len(horsemen) - 1, which is
the index of the last element. When i is equal to len(horsemen), the condition
fails and the body is not executed, which is a good thing, because len(horsemen)
is not a legal index.
Although a list can contain another list, the nested list still counts as a single
element. The length of this list is four:
[’spam!’, 1, [’Brie’, ’Roquefort’, ’Pol le Veq’], [1, 2, 3]]
Explanation / Answer
horsemen = ["war", "famine", "pestilence", "death"] i = 0 while iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.