Ask Your Question
1

Sage Range function

asked 2017-09-17 19:49:48 +0100

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

I use sage range function to print numbers form 1 to say 10 using print [1..10]. How to print only even numbers using this?

edit retag flag offensive close merge delete

Comments

1

Is the following ok?

sage: print range(2,11,2)
[2, 4, 6, 8, 10]
dan_fulea gravatar imagedan_fulea ( 2017-09-17 20:06:12 +0100 )edit

I knew that. I was wondering if same can be done with [1..10]?

Manoj gravatar imageManoj ( 2017-09-17 20:28:54 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
4

answered 2017-09-17 21:16:57 +0100

slelievre gravatar image

The ellipsis operator looks at the previous two numbers to guess the step.

sage: [2, 4 .. 10]
[2, 4, 6, 8, 10]
edit flag offensive delete link more

Comments

wow, i didn't know that works!

mforets gravatar imagemforets ( 2017-09-17 21:19:03 +0100 )edit

Thanks....

Manoj gravatar imageManoj ( 2017-09-17 21:37:07 +0100 )edit
0

answered 2017-09-17 21:16:13 +0100

mforets gravatar image

using list comprehension:

sage: [i for i in [1..10] if i%2==0]
[2, 4, 6, 8, 10]

see more alternatives in the Programming in Python and Sage Thematic Tutorial.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2017-09-17 19:49:48 +0100

Seen: 3,394 times

Last updated: Sep 17 '17