t0m3k
t0m3k

Reputation: 317

What's the best way to specify an unknown index?

I'm pulling data from Google sheets with this:

for x in range(0, 3):
    gmap.marker(latitude[x], longitude[x], title=boxnumber[x])

There are only three values in each column to pull. So, the above code works well. However, if I have four like this:

for x in range(0, 4):

I get List index out of range... The problem is, I don't know what my second number/list index will be. This number may be 25 tomorrow, or maybe 60. What's the best way to deal with this? For example, if I have 50 in my list, how can I get the for loop to call 50 automatically? Is there a way to call (0, #ofavailable)?

Upvotes: 0

Views: 588

Answers (3)

Red
Red

Reputation: 27577

You can use enumerate():

for x,y in enumerate(latitude):
    gmap.marker(latitude[x], longitude[x], title=boxnumber[x])

Upvotes: 1

sabraship
sabraship

Reputation: 99

You could do len(list), which would give the length of your list. You could also, instead of for x in range(0, len(list)):, just do for x in list: which would give you the item at each index, instead of just the index, if that's simpler for your project.

Upvotes: 1

Barmar
Barmar

Reputation: 781706

Use len() to get the length of the lists (I assume they're all the same length).

for x in range(len(latitude)):
    gmap.marker(latitude[x], longitude[x], title=boxnumber[x])

Or zip all the lists together:

for lat, lon, title in zip(latitude, longitude, boxnumber):
    gmap.marker(lat, lon, title=title)

You should also consider putting everything into a single list of dictionaries or tuples, rather than separate lists for each value.

Upvotes: 2

Related Questions