Home > Backend Development > Python Tutorial > 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
Release: 2024-11-19 06:24:03
Original
1073 people have browsed it

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)
    Copy after login
  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.
    Copy after login
  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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template