Home  >  Article  >  Backend Development  >  How to Fix the 'TypeError: List Indices Must Be Integers or Slices, Not Str' Error in Python?

How to Fix the 'TypeError: List Indices Must Be Integers or Slices, Not Str' Error in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 06:24:031005browse

How to Fix the

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:

  1. Convert the length of the second list (array_dates) to an integer, as indices must always be integers.

    array_length = len(array_dates)
  2. 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.
  3. Remove the line i = 1 from your loop, as it's no longer necessary.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn