1

I want to write a function which will return indices of 2D array. I was guessing if I should return tuple or list. So I quickly tried to index 2D list using tuple and list:

>>> strw = [['1','2'],['3','4']]
>>> strw = [list(map(int, i)) for i in strw]
>>> strw
[[1, 2], [3, 4]]

Indexing above list using tuple gives error:

>>> tpl = (1,1)
>>> strw[tpl[0],tpl[1]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple

Indexing list using another list also gives error:

>>> lst = [1,1]
>>> strw[lst[0],lst[1]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple

Q1. How can I resolve this? Is there any standard approach to this (returning indexes from function)?

(Q2. Also somewhat unrelated question: how can I load file containing space separated ints into int array, instead of first creating string array with something like below and then mapping individual element to ints:

with open(_file_path) as textFile:
        strw = [line.split() for line in textFile]
Andreas
  • 8,694
  • 3
  • 14
  • 38
Rnj
  • 1,067
  • 1
  • 8
  • 23
  • 2
    You need `strw[tpl[0]][tpl[1]]` rather than `strw[tpl[0],tpl[1]]`. A list of lists is still a list and hence takes a single index, not two. The returned list can itself be subscripted, which is what `strw[tpl[0]][tpl[1]]` does. – John Coleman Oct 22 '20 at 23:20
  • 2
    second questions pleas into a new question, dont ask 2 questions at the same time. – Andreas Oct 22 '20 at 23:22
  • `mylist[1,2]` is not the right syntax for accessing items in a nested list. Use `mylist[1][2]` instead. – John Gordon Oct 22 '20 at 23:26

0 Answers0