ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 17 Mar 2021 12:52:15 +0100List not calablehttps://ask.sagemath.org/question/56208/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] = 3`and 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 helpWed, 17 Mar 2021 11:19:29 +0100https://ask.sagemath.org/question/56208/list-not-calable/Answer by tmonteil for <p>The following code doesn't work since <code>List[i][j]</code> seems not to be recognized as an integer</p>
<pre><code>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))]
</code></pre>
<p><code>List[1][1] = 3</code>and its type is integer so I was persuaded that I can call cand(List[1][1]) but i seems that it dosn't work.</p>
<p>Need a little help</p>
https://ask.sagemath.org/question/56208/list-not-calable/?answer=56209#post-id-56209There 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.
Wed, 17 Mar 2021 12:52:15 +0100https://ask.sagemath.org/question/56208/list-not-calable/?answer=56209#post-id-56209