# List not calable

The following code doesn't work since List[i][j] seems not to be recognized as an integer

cand=["A","B","C","D"]
List=[[],[0,3],[0,1,3],[0]]
L=[[cand(List[i][j]) for j in range(len(i))] for i in range(len(List))]


List[1][1] = 3and its type is integer so I was persuaded that I can call cand(List[1][1]) but i seems that it dosn't work.

Need a little help

edit retag close merge delete

Sort by » oldest newest most voted

There are various problems in your las line:

• i is an integer (produced by the range function), so len(i) has no meaning
• cand is a list so cand(...) has no meaning, instead, you should use cand[...]
• j should not range over [0,...i-1] but over [0,...List[i]-1]

If we fix all the 3 issues, we get:

sage: L=[[cand[List[i][j]] for j in range(len(List[i]))] for i in range(len(List))]
sage: L
[[], ['A', 'D'], ['A', 'B', 'D'], ['A']]


That said, iterating over the elements of a list by looking to its length and calling its items by ranging over its indices is a wrong habit.

It turns out that in Python, the lists are iterable, which means that you can loop directly over elements of a list, which means that if L is a list, you can do: for i in L instead of for j in len(L): i = L[j]

So, if we keep the structure of your loop, by just removing the range noise, we get:

sage: L = [[cand[b] for b in a] for a in List]
sage: L
[[], ['A', 'D'], ['A', 'B', 'D'], ['A']]


As you can see, it is more compact, more readable, and there is no risk to use out of range indices.

more