Lists are collections of data, i.e. arrays of memory cells
| 7 | 2 | 4 | 2 | 6 |
A programmer can create a list with a single statement:
list=['a','b','c']
You can also insert things in existing lists:
append -- appends a new element to the end of a list.
list = [1,2,3]
list.append(4)
print list
[1,2,3,4]
insert -- inserts an element somewhere in the list.
list.insert(2,99) # put 99 in the 2nd slot.
print list
[1,2,99,3,4]
Indexing -- use an index to modify an existing element.
list[1]=83
You can initialize lists by assigning a list to the empty list [ ], e.g.,
list=[]
Note that you need to initialize a list before calling 'append'-- You can't append to a list that hasn't been initialized either with an empty or non-empty list (e.g., list=[1,2,3]
You also cannot access/modify an element of a list unless the list already has that element. So the following code will give an error:
list=[]
list[0]=4 # error
list2=[1,2]
list2[3]=7 # error
The following statement does NOT make a copy of a list:
list1=list2
It creates an alias-- both variables will point at the same contents. Consider the following code:
list1=[1,2,3]
list2=list1 # ***
list2[1]=55
Both list1 will print as [1,55,3]
You can create a copy of a list using a statement like the following:
list2=list1[:]
If this line replaces *** in the code above, list1 will not be modified when list2 is.
The ':' syntax is an example of 'get range' operation of a list.
list2=list1[0:1] # returns a list containing the first two elements of list1.
1. Which of the following will cause errors? Enter them in the interpreter to check.
a. list1[0]='abc'
b. list2=[1,2,3]
list2[3]=4
c. list2=[1,2,3]
list2.insert(3,4)
d. list2=[1,2,3]
list2.append(4)
2. Write a program that reads in 5 numbers from the end-user into a list, then computes the average of those numbers. For this exercise, do not total the numbers as you read them. Instead, use one loop to read in five numbers into a list, and a separate loop to compute the total of the elements in the list.