Sobes.tech
Junior — Middle

Can you use a while loop to iterate over collection elements?

sobes.tech AI

Answer from AI

Yes, in Python, you can use a while loop to iterate over collection elements, but it is not the most common method. Usually, a for loop is used for iterating over collections because it is simpler and more readable.

If you still need to use while, you can iterate over a collection by index if the collection is indexable (for example, a list):

items = ['a', 'b', 'c']
i = 0
while i < len(items):
    print(items[i])
    i += 1

For collections that do not support indexing (such as sets or generators), using while is inconvenient. In such cases, it is better to use a for loop or convert the collection to a list.

You can also use an iterator with next() and a while loop:

items = ['a', 'b', 'c']
iterator = iter(items)

while True:
    try:
        item = next(iterator)
        print(item)
    except StopIteration:
        break

Thus, while can be used, but for is generally preferred.