next up previous contents
Next: Removing elements from a Up: Lists, sequences, via for Previous: Using for loops   Contents

Using if-then statements

What if your list is not created by a formula, like $i\longmapsto i^2$, but instead by a condition, like ``all primes $p$ for which $4$ divides $p-3$ and $1\leq p\leq 100$''? One way is to add a conditional statement to the for-loop, for example:

> L:=[];         
> for i in [1..100] do
for> if IsPrime(i) and i mod 4 eq 3 then
for|if> L:=Append(L,i);
for|if> end if;
for> end for;
> L;
[ 3, 7, 11, 19, 23, 31, 43, 47, 59, 67, 71, 79, 83 ]

Exercise 5 (a)   Find the number of primes which are $<1000$.

To find a subsequence of a sequence $S$ satisfying a property $P$, use the $[x \ :\ x\ {\rm in}\ S\ \vert\ P(x)]$. For example, to find all the elements in List1 which are less than or equal to 4, type

> List1:=[2^i:i in [1..3]];  
> List1_2:=[j : j in List1 | j le 4];           
> List1_2;
[ 2, 4 ]

Exercise 6   Create the sequence of all integers from $-20$ to $20$. Next create the subset those elements which are even.



David Joyner 2001-08-22