"SyntaxWarning: list indices must be integers or slices, not tuple"

Hey guys,
I’m trying to resolve some error here:

This is my error:

“SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?”

This is the culprit:
np.array([self[global_list_of_pairs[pair]]for pair in pairs_list][…, :2], np.int32)

I’m wondering. How come […,:2] doesn’t work correctly?

Thanks

1 Like

Where the code says

What do you think this part means? What kind of thing do you expect to get as a result?

Why should it then be possible to apply [...,:2] to that? What should the result look like, and why?

1 Like

This is my error:
“SyntaxWarning: list indices must be integers or slices, not tuple;
perhaps you missed a comma?”

This is the culprit:
np.array([self[global_list_of_pairs[pair]]for pair in pairs_list][…, :2], np.int32)

I think modern SyntaxErrors underline the offending item.

I’m wondering. How come […,:2] doesn’t work correctly?

That would b because [...,:2] is a special indexing form used by a
numpy array, and not by a list. I think your bracketing is incorrect.

First up, deconstruct things:

  • the tuple is, as you identify, [...,:2] being a 2-tuple of an
    Ellipsis (...) and a slice (:2)
  • what you’re indexing with it is the [self...for pair in pairs_list]
    list comprehension, whose result is as you might imagine, a Python
    list
  • the error actually says: “list indices must be integers or slices, not
    tuple”
  • because it is a SyntaxError it means Python itself has identified the
    issue as parse time (this is recnet; in my Python 3.10 here is parses
    ok and makes a TypeError at run time), so there must be a thing
    which is syntacticly guarrenteed to be a list, and that is the list
    comprehension

So, this means:

  • ...,:2 is valid syntax, being a 2-tuple
  • [...,:2] is also valid, because that’s just the indexing operator
    being passed the tuple; what it means depends on what you’re indexing
  • so some expression foo[..,:2] is also valid

This implies the [...,:2] needs to be appled to a differnet object.

I think you want something shaped like this:

 np.array([self.......], np.int32)[...,:2]

i.e. you want to index the numpy array, not the list comprehension,
because numpy array support this particular special index form. (Note:
sorry, the ....... is just an indicator of the rest of the list
comprehension, but the ... is the real ellipsis of your original
expression.)

Cheers,
Cameron Simpson cs@cskk.id.au

I think what you actually want

4 Likes