170k views
0 votes
What is another way to write this line of code? for i in [0, 1, 2]:

User Tom Pester
by
8.0k points

1 Answer

2 votes

Final answer:

The original line of code can be rewritten as 'for i in range(3):', which is more concise and Pythonic, achieving the same result using the range function to iterate through the numbers 0 to 2.

Step-by-step explanation:

The original line of code you've provided is using a hard-coded list to iterate through the values 0, 1, and 2. An alternative way to write this using Python's range function is:

for i in range(3):

This line of code will produce the same results as your original loop. The range function generates a sequence of numbers, which by default starts at 0 and increments by 1 each time, up until but not including the number you provide (in this case, 3). It's a more concise and Pythonic way to write loops that iterate over a sequence of numbers.

User Melculetz
by
7.8k points