Programmers learn & share
+1 vote
363 views

Problem :

 I'm a newbie with Python's arrays and I don't understand how I can avoid below error:
python typeerror: list indices must be integers or slices, not str
by (6.9k points)   | 363 views

3 Answers

0 votes

Solution :

Please Note array_length should be an integer and not a string:

array_length = len(array_dates)

Also note, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the bellow line:

i += 1

Further Readings:

https://github.com/uber/ludwig/issues/76

by (36.1k points)  
edited by
0 votes

Every element in python has a unique position. These positions are defined by index and these indexes are always represented by using integers. You have declared a variable that has an index value of the list element. But if the element does not have integer value instead has a string value. Then the following error occurs;

“TypeError: list indices must be integer or slices, not str”.

Solution:

To avoid this error, it is suggested that always assign an integer value to a variable.

Example:

To better understand this error lets look at an example:

# Declare a list

list1 = ['Physics','Chemistry', 'Biology']

# Declare an index variable

index = '1'

print('Value at List Index 1', list1[index])

Output:

Traceback (most recent call last):

 File "list-error.py", line 5, in <module>

  print('Value at List Index 1', list1[index])

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

Correct Example:

# Initialise a list

list1 = ['Physics','Chemistry', 'Biology']

# Declare an index variable

index = 1

print('Value at List Index 1', list1[index])

Output:

Value at List Index 1 physics

Note:

If you are using a variable for specifying the index of a list element, then make sure it must have an integer value. Otherwise, you can directly access an element using the indices.

by (2.8k points)  
0 votes

Solution:

1st , array_length must be an integer and not a string

array_length = len(array_dates)

2nd , Your for loop must be constructed using range

for i in range(array_length):  # Use `xrange` for python 2.

3rd, i will increment automatically

i += 1

 

Follow the below example

# Inilised a list 
list1 = ['Hi', 'This', 'is','STechies']

# Inilised variable i as 0
i = 0

# Inilised empty string
string1 = ''

# Run While loop to list length
while i < len(list1):
    # Joint each value of list to final string
    string1 = string1 + ' ' + list1[i]
    i += 1

# Print final Output
print(string1)

 

Output

Hi This is STechies

 

by (11.2k points)  
2,228 questions
2,738 answers
59 comments
241 users