How can I fix the `TypeError: list indices must be integers or slices, not str` in Python?

I’m trying to merge two lists (array_urls and array_dates) into a single array and write it to a CSV file. My current code gives this error:

array_length = str(len(array_dates))

for i in array_length:
    result_array[i][0].append(array_urls[i])
    result_array[i][1].append(array_dates[i])

Error message:

TypeError: list indices must be integers or slices, not str

It seems my counting or indexing is causing the problem. How can I fix this list indices must be integers or slices, not str issue and correctly merge the lists?

Hey! I’ve run into this exact error :sweat_smile:. The issue is here:

array_length = str(len(array_dates))
for i in array_length:

len(array_dates) gives an integer, but you converted it to a string.

Iterating over a string gives characters, which are strings—hence the TypeError when used as a list index.

Fix it like this:


for i in range(len(array_dates)):
    result_array[i][0].append(array_urls[i])
    result_array[i][1].append(array_dates[i])

range(len(...)) generates integers, which are valid list indices.

This is the most common fix I use for indexing errors like this.

I personally prefer using zip, it avoids manual indexing and is more Pythonic:

result_array = []

for url, date in zip(array_urls, array_dates):
    result_array.append([url, date])

Now result_array is a list of lists where each element contains a URL and its corresponding date.

Much cleaner and less error-prone than manually indexing.

For a one-liner approach, I often do:

result_array = [[url, date] for url, date in zip(array_urls, array_dates)]

Produces the same merged list.

Works perfectly for writing to a CSV with csv.writer:

import csv

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(result_array)