Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168745
Image: ubuntu2004

SEQUENCE TYPES: lists, ranges and strings

LISTS

1. A list can be defined with square brackets. The list can be empty, or you can initialize the list with any number of items separated by commas

          new_list_object = [element_1, element_2, element_3]

       empty_list = []

2. the append method adds a new item to the end of the list

      empty_list.append(new_item)

3. the extend method adds multiple elements to the end of the list

      empty_list.extend([list_of_items])

# Creating lists with Python list1 = ['a', 'b', 'c', 'd', 'e'] print("A list of characters: " + str(list1))
A list of characters: ['a', 'b', 'c', 'd', 'e']
list1[0]
'a'
list1[1:4]
['b', 'c', 'd']
list1[-3]
'c'
list1[-3:]
['c', 'd', 'e']
list2 = [] print("An empty list: " + str(list2)) list2.append('f') list2.append('g') print("After appending items: " + str(list2))
An empty list: [] After appending items: ['f', 'g']

 

Extend adds each item to the list, while append adds the entire list as a single item!!!

list3 = list() list3.extend(list1) print("List 3 after extending: " + str(list3))
List 3 after extending: ['a', 'b', 'c', 'd', 'e']
list3.append(list2) print("List 3 after appending a list:" + str(list3)
List 3 after appending a list:['a', 'b', 'c', 'd', 'e', ['f', 'g']]

 

RANGE - returns a list of integers that starts at zero and increments by one until it reaches (but does not include) the specified value.

# from 0 to 10, without 10 range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# from 5 to 10 without 10 range(5,10)
[5, 6, 7, 8, 9]
# from 3 to 10 with step 2 and without 10 range(3,10,2)
[3, 5, 7, 9]
list_of_ints = range(1, 11, 2) print("A list of integers: " + str(list_of_ints))
A list of integers: [1, 3, 5, 7, 9]

 

Another shortcut for creating a list of integers that is similar to the range function:

      [start_value..endpoint, step=1]

list_of_ints_2 = [1..11, step=2] print("Another list of integers: " + str(list_of_ints_2))
Another list of integers: [1, 3, 5, 7, 9, 11]
a = [1,3,5,7,9,11] b = [0,2,4,6,8,10] print(a[1]) print(a[0:4]) print(a[-1]) print(a[-4:-1]) print(a[-4:])
3 [1, 3, 5, 7] 11 [5, 7, 9] [5, 7, 9, 11]
a[0] = 3.7324 print(a)
[3.73240000000000, 3, 5, 7, 9, 11]
a[0:3] = b[0:3] print(a)
[0, 2, 4, 7, 9, 11]
b[-2:] = [] print(b)
[0, 2, 4, 6]

 

STRINGS - they have all the features of sequence types

first_name = 'John' last_name = 'Smith' full_name = first_name + ' ' + last_name print(full_name) print(len(full_name)) print(full_name[:len(first_name)]) print(full_name[-len(last_name):]) print(full_name.upper()) print('')
John Smith 10 John Smith JOHN SMITH

 

FOR loop - A Python for loop iterates over the items in a list.

for loop_variable in list_name:
    statement 1
    statement 2

Let's say you have some data stored in a list, and you want to print the data in a particular format. We will use three variations of the for loop to display the data.

time_values = [0.0, 1.5, 2.6, 3.1] sensor_voltage = [0.0, -0.10134, -0.27, -0.39]
print("Iterating over a single list:") for value in sensor_voltage: print(str(value) + " V")
Iterating over a single list: 0.000000000000000 V -0.101340000000000 V -0.270000000000000 V -0.390000000000000 V

 

zip accepts one or more sequence types (with the same number of elements) as arguments and returns a list of tuples, where each tuple is composed of the one element from each sequence.

The syntax time,value was used to unpack each tuple, so that we could access the values through the variables time and value.

print("Iterating over multiple lists:") for time, value in zip(time_values, sensor_voltage): print(str(time) + " sec " + str(value) + " V")
Iterating over multiple lists: 0.000000000000000 sec 0.000000000000000 V 1.50000000000000 sec -0.101340000000000 V 2.60000000000000 sec -0.270000000000000 V 3.10000000000000 sec -0.390000000000000 V

 

for loop_counter in range(len(list_name)):
     statement 1
     statement 2

print("Iterating with an index variable:") for i in range(len(sensor_voltage)): print(str(time_values[i]) + " sec " + str(sensor_voltage[i]) + " V")
Iterating with an index variable: 0.000000000000000 sec 0.000000000000000 V 1.50000000000000 sec -0.101340000000000 V 2.60000000000000 sec -0.270000000000000 V 3.10000000000000 sec -0.390000000000000 V

 

Two simple examples of for loops:

sum = 0 for i in range(10): sum += i print(sum)
45

 

How many lines will be printed when the following loop runs?

for i in range(3): for j in range(4): print("line printed")
line printed line printed line printed line printed line printed line printed line printed line printed line printed line printed line printed line printed
list1 = [' a ', ' b ', 'c '] list1_stripped = [] for s in list1: list1_stripped.append(s.strip()) print(list1_stripped)
['a', 'b', 'c']

We defined a list of strings, each of which contained whitespace before and/or after the character.

The string method strip was used to remove the whitespace from each string, and we used the list method append to create a new list of stripped strings.

LIST COMPREHENSION - general sintax

new_list = [ operation_on_value for value in existing_list ]

list1_stripped_2 = [s.strip() for s in list1] print(list1_stripped_2)
['a', 'b', 'c']

 

If you are creating a new list, then the existing list can be generated by a function like range or srange.

list2 = [] for val in srange(0.0, 10.0, 1.0): if val % 2 == 0: list2.append(numerical_approx(val**2, digits=3)) print(list2)
[0.000, 4.00, 16.0, 36.0, 64.0]

 

WHILE loopis used when we don't know how many iterations will be required and in that case we can't use FOR loop!

WHILE conditional_expresion:
    statement 1
    statement 2

The loop iterates as long as the conditional expression evaluates to the value True.
The loop terminates as soon as the expression evaluates to False.

N = 12928 while N % 2 == 0: N = N/2 print N
6464 3232 1616 808 404 202 101

 

IF statement - allow a program to make decisions while it is running.

if conditional_expression:
   statements
else:
   statements

def factor(n): d = 2 while n > 1: if n % d == 0: n = n/d print d, else: d = d + 1
n=123456789 factor(n)
3 3 3607 3803
factor(8)
2 2 2
def factor2(n): d = 2 F = [ ] while n > 1: if n % d == 0: n = n/d F.append(d) else: d = d + 1 return F
factor2(123456789)
[3, 3, 3607, 3803]
3*3*3607*3803
123456789

 

ELIF instead of SWITCH

solution_type = "numerical" if solution_type == "analytical": print('analytical') elif solution_type == "numerical": print("numerical") elif solution_type == "symbolic": print("symbolic") else: print("ERROR: invalid solution type")
numerical