Home > Mobile >  how to fix error "tuple indices must be integers or slices, not list"
how to fix error "tuple indices must be integers or slices, not list"

Time:06-28

i have this code

#fsa and ghf are both lists of equal length

#this code divides each of the elements within each list into multiple lists in six element intervals
start = 0
end = len(fsa)
for x in range(start,end,6):
    l = fsa[x:x 6], [x]
    m = ghf[x:x 6], [x]

# this code should be able to fetch the first and last element in those lists of six for 'ghf'(but i can't seem to make it work)

for x in m:
    m1 = m[x]
    m2 = m[x 5]

    print(m1, m2)

Whenever i run that last code i get this error

Traceback (most recent call last):
  File "C:\Users\nkosi\PycharmProjects\Fmark 1\venv\mark 1.py", line 53, in <module>
    m1 = m[x]
TypeError: tuple indices must be integers or slices, not list

please help me resolve this issue.

CodePudding user response:

m is a tuple and x is a list.

You can't index a tuple with a list. You have to use an int or slice.

CodePudding user response:

you want to make l and m two lists, but with this code you're just reassigning new values to that variables. so you have at first to declare them:

start = 0
end = len(fsa)
l = []
m = []

and then append values to the lists:

for x in range(start,end,6):
    l.append(fsa[x:x 6])
    m.append(ghf[x:x 6])

then, if you want to take the first and last element (I'll do as in the example, where you only want the first and last of each element of m, and not also of l), given that the length of each little list is 6:

for x in m:
    m1 = m[0]
    m2 = m[5]

    print(m1, m2)
  • Related