Home > Article > Backend Development > How to Fix the 'TypeError: List Indices Must Be Integers or Slices, Not Str' Error in Python?
TypeError: List Indices Must Be Integers
The error "TypeError: list indices must be integers or slices, not str" occurs when you attempt to access a list item using a string index instead of an integer or slice. This error is common when merging two lists into a single array for CSV export.
To avoid this error, follow these steps:
Convert the length of the second list (array_dates) to an integer, as indices must always be integers.
array_length = len(array_dates)
Iterate through the new array_length integer using the range function, which automatically increments the iterator value.
for i in range(array_length): # Use `xrange` for Python 2.
You can also streamline your code by using zip to combine the two lists, since they have the same length:
result_array = zip(array_dates, array_urls) csv_file.writerows(result_array)
Here's the corrected code:
def fill_csv(self, array_urls, array_dates, csv_file_path): array_length = len(array_dates) # We fill the CSV file with open(csv_file_path, "w") as file: csv_file = csv.writer(file, delimiter=';', lineterminator='\n') # We merge the two arrays in one result_array = [] for i in range(array_length): result_array[i][0].append(array_urls[i]) result_array[i][1].append(array_dates[i]) csv_file.writerows(result_array)
The above is the detailed content of How to Fix the 'TypeError: List Indices Must Be Integers or Slices, Not Str' Error in Python?. For more information, please follow other related articles on the PHP Chinese website!