简体   繁体   中英

How do you write a while loop using count on Python?

If a list of numbers can be defined as follows:

 x=[22,25,45,32,21]

Then, using the while loop count the number of items in the list. Print the final count.

I am having trouble. I'm trying to write it using count and len() function. Is there another way besides len() function. Thanks.

If you can't use len , consider that:

  1. You can use things like x.pop() or del x[0] to remove an item from the list.

  2. tuple(x) == tuple() (or equivalently, tuple(x) == tuple([]) ) is True for a list x when and only when x is empty.

And, if you need to keep the original list intact, you can use xcopy = x[:] to make a shallow copy of x and use the above method on xcopy .

This is homework but here is a solution:

x=[22,25,45,32,21]

counter = 0
while counter < len(x):
    counter += 1

print(counter)
#5

Without while:

counter = 0
for i in x:
    counter +=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM