Ask Your Question

Revision history [back]

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.