0

I`m trying to append an list of the indexes of another list.

I have one list with random numbers, and need to create another list, with the indexes of the first list.

My code is just like this:

from random import seed
from random import randint
seed(715)
g1 = []
g2 = []
for v in range(20328):
valor = randint(40, 220)
g1.append(valor)


for v in enumerate(g1):
    g2.append(v)

print("v g1[v] g2[v] g1[g2[v]]")
for v in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
    print(v, g1[v], g2[v], g1[g2[v]])

But I get the error below:

print(v, g1[v], g2[v], g1[g2[v]])
TypeError: list indices must be integers or slices, not tuple

What am i doing wrong?

1
  • 5
    Because g2 list contains tuples due to enumerate. Commented Nov 6, 2018 at 19:19

5 Answers 5

1

g2 is set as a list of tuples in your program, not integers. If you use print(g2[0]) to see what's inside you'll get something like g2[0]:(0, 69) which is a tuple. So that's the problem.

You can use any of the following to resolve the issue:

for v in enumerate(g1):
    g2.append(v[1])

or

for index, value in enumerate(g1):
    g2.append(value)

or

for value in g1:
    g2.append(value)

Helpful resource: https://docs.python.org/3/library/functions.html#enumerate

Sign up to request clarification or add additional context in comments.

Comments

0

you are using enumerate to fill g2 with tuples, enumarate will give you the index and the value as a tuple, so whenever you call g2[v], you won't get the index only, you will get a tuple of (index, value). If you want the index only in g2, you should use something like the following the create g2.

for i, v in enumerate(g1):
    g2.append(i)

Comments

0

Like Sandeep Kadapa said, g2 gets turned into a tuple, so try to do something like,

list(g2)

after the enumerate and before the print functions are called.

Comments

0

Maybe you need to add only indexes to the second list?

for index, v in enumerate(g1):
    g2.append(index)

Btw I would replace that function with something like that:

g2 = list(range(len(g1))

Let me know if it works for you

Comments

0

Enumerate in your code sets v as a tuple. You produce the index and the element with the following format:

for count, v in enumerate(g1):
    g2.append(count)

where count will be the index of g1, and v will be the element at that index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.