# If Comprehension in list

Hello,

I am knew to SageMath and Python. I hope to learn Python after I finish C++.

I would like to compare two lists and place the larger value from list L2 in another list if it is greater than L3 but not in the list if less than. Here is my try:

L2 =[sum(divisors(i))-i for i in range(1,100,1)]
print L2

L3 =[i for i in range(1,100,1)]
print L3

L4 =[L2[i] if L2[i] > L3[i] for i in range(1,100,1)]
print L4


I get the following error:

File "<ipython-input-1-01c49b9c5559>", line 20
L4 =[L2[i] if L2[i] > L3[i] for i in range(Integer(1),Integer(100),Integer(1))]
^
SyntaxError: invalid syntax

edit retag close merge delete

Sort by » oldest newest most voted

the syntax for list comprehension with a condition is to write the if clause after the loop iterable, for example:

sage: [i for i in srange(-3, 3) if i^2 == 4]
[-2, 2]


then:

sage: L2 = [sum(divisors(i))-i for i in srange(1, 100, include_endpoint=True)]
sage: L3 = srange(1, 100, include_endpoint=True)
sage: L4 = [L2i for i, L2i in enumerate(L2) if L2[i] > L3[i]]
sage: L4
[16, 21, 22, 36, 42, 55, 50, 54, 76, 66, 64, 108, 78, 74, 123, 90, 106, 140, 92, 144, 156, 117]


for this use and further learning material, consider giving a try to the Programming in Python and Sage Thematic Tutorial. there even are exercises!

more

The question is an explicit one about how to compare two lists and make a third one out of them.

However, when programming some general considerents have priority. For instance, keep things simple. In this example case, the operation of associating the list L3 is really not indicated, what shall we do with its elements? (And even if... why not directly L3 = range(1,100)? And why redefine the one letter variable i which traditionally stays for $\sqrt{-1}$. This was the first point. Then there is an internal function computing the sum of divisors. Why not use it? Shall we consider that we have to first compute all divisors, than add them is the quick way to do the job?

Why do we need L2 ? (As a list, why do we not work elementwise.) Just to see we can associate this list as an example?!

An alternative way to get L4 without using list comprehension would be for example in sage:

L4 = []
for k in [1..100]:
s = sigma(k) - k
if s > k:
# print "%s = %s -> %s" % ( k, k.factor(), s )
L4.append( s )

print L4


This gives:

[16, 21, 22, 36, 42, 55, 50, 54, 76, 66, 64, 108, 78, 74, 123, 90, 106, 140, 92, 144, 156, 117]


(And of course, now we do not know which sum comes from which $k$... We could use in the above some intermediate prints to catch this information. Then why associate a list of $100$ elements, when finally their number is smaller?)

Note: This post may not answer the question directly, but it is one in a series of posts, where we simply ignore there is already a function sigma doing half of the job.

more