-3

There is a task like this:

I have a list:

a = ["1", "2"]

And the for loop:

for i in range(0, 2):
    print(a[i])

But if the list is with one element:

a = ["1"]

then there will be an error: IndexError: list index out of range

What can be done to keep the structure

for i in range(0, 2):
Deprool
  • 75
  • 8
  • 4
    Why do you hard-code the range in the first place? This seems like an XY problem. – Barmar May 26 '23 at 16:46
  • @Barmar I guess sometimes you just want to eyeball the first few elements of a list? A bit like doing .head() in pandas... – slothrop May 26 '23 at 16:53
  • Where the code says `for i in range(0, 2):`, what exactly do you think this means? Why should it say `range(0, 2)`, and not any other numbers? Exactly what should happen when there is 1 item in the list? Exactly what should happen when there are **no** items in the list? Exactly what should happen when there are **more than two** items in the list? – Karl Knechtel May 26 '23 at 18:19

4 Answers4

2

Iterate over the list directly:

a = ["1", "2"]

for i in a:
    print(i)

If you specifically want to iterate over the indices of a rather than its elements (note that most of the time this is unnecessarily complicated and you shouldn't do it), build your range based on the len of a rather than specifying a hardcoded number like 2:

for i in range(len(a)):
    print(a[i])
Samwise
  • 68,105
  • 3
  • 30
  • 44
2

You can handle this with a try:except block

a = ["1"]

for i in range(0, 2):
    try:
        print(a[i])
    except IndexError:
        break 

But in general it's better to iterate over the list itself

for i in a:
    print(i)
JRiggles
  • 4,847
  • 1
  • 12
  • 27
1

You might use for without range, but just with list instance, e.g.

print("list with many elements")
a = ["1","2","3"]
for i in a:
    print(i)
print("list with one element")
b = ["1"]
for i in b:
    print(i)

gives output

list with many elements
1
2
3
list with one element
1
Daweo
  • 31,313
  • 3
  • 12
  • 25
0

Instead of iterating over a range of indexes, iterate directly over a slice of the list. The useful thing here is that, for example, lst[:10] doesn't fail if the list has fewer than 10 elements - it just gives all the elements.

So in your case:

a = ["1"]
for x in a[:2]:
    print(x)

which prints just 1 as you intend.

This is one of many reasons why you should prefer loops like for object in collection instead of for index in range_of_indexes.

slothrop
  • 3,218
  • 1
  • 18
  • 11