2021.08.27 MATH 3600 Loops and lists

90 days ago by calkin

L=[0,1,2,3,x] 
       
print(L) 
       
[0, 1, 2, 3, x]
[0, 1, 2, 3, x]

Sage indexes from 0.  This means that L[4] is "x".

print(L[1]) 
       
1
1
print(L[4]) 
       
x
x
M=[9,7,5] 
       
L+M 
       
[0, 1, 2, 3, x, 9, 7, 5]
[0, 1, 2, 3, x, 9, 7, 5]
len(L+M) 
       
8
8

If we want the list of all integers in a range, we can use range(), or, better, srange()

print(range(1,5)) print(srange(1,5)) 
       
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
type(range(4)[0]) 
       
<type 'int'>
<type 'int'>
type(srange(4)[0]) 
       
<type 'sage.rings.integer.Integer'>
<type 'sage.rings.integer.Integer'>
srange(10) 
       
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We can step through the elements of a list using a for loop.

print(L) 
       
[0, 1, 2, 3, x]
[0, 1, 2, 3, x]
for i in L: print(i^2) 
       
0
1
4
9
x^2
0
1
4
9
x^2
for i in srange(10): if i.is_prime(): print(i) print(i^2+1) 
       
2
5
3
10
5
26
7
50
2
5
3
10
5
26
7
50

Much of what we do in this course will be manipulating lists.

We've seen concatenating lists using 

L.append(x+3) 
       
print(L) 
       
[0, 1, 2, 3, x, x + 3]
[0, 1, 2, 3, x, x + 3]
L.count(1+2+x) 
       
1
1
L.index(7) 
       
Traceback (click to the left of this block for traceback)
...
ValueError: 7 is not in list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_37.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("TC5pbmRleCg3KQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmp5UEC19/___code___.py", line 3, in <module>
    exec compile(u'L.index(_sage_const_7 )
  File "", line 1, in <module>
    
ValueError: 7 is not in list
L.insert(5,x-1) 
       
print(L) 
       
[0, 1, 2, 3, x, x - 1, x + 3]
[0, 1, 2, 3, x, x - 1, x + 3]
L[5] 
       
x - 1
x - 1
a=L.pop(5) 
       
print(a) 
       
x - 1
x - 1
print(L) 
       
[0, 1, 2, 3, x, x + 3]
[0, 1, 2, 3, x, x + 3]
L.reverse() print(L) 
       
[x + 3, x, 3, 2, 1, 0]
[x + 3, x, 3, 2, 1, 0]
L.reverse() print(L) 
       
[0, 1, 2, 3, x, x + 3]
[0, 1, 2, 3, x, x + 3]
print(M) 
       
[9, 7, 5]
[9, 7, 5]
M.sort() 
       
print(M) 
       
[5, 7, 9]
[5, 7, 9]