Transcript ppt

CSC 1010
Programming for All
Lecture 6
Lists
Introduction – Why Lists
• Lists group like items
• Lists give one name to the group
• You can refer to the whole group using one name
– Store an ordered list of int or float or strings
– Declare one variable that can hold multiple, individual
accessible values
• Loops make it easy to process a group of like items
Store a Group of 6 values
value1 = 2
value2 =17
value3 = 5
value4 = 43
value4 = 23
value5 =12
value6 = 4
or ---- we use a list
Declaring an empty list
• Declare an empty list with a list name and square
brackets
• Example:
myList=[]
• myList is a structure capable of storing many values
Declare a list with 6 values
values=[2,17,5,43,23,12]
Declare a list with 6 values
values=[2,17,5,43,23,12]
List name
List values
Index of List
• Each slot
– Referenced using a numerical index
• Index
– 0 to N-1
– N is the size of the list (total number of elements)
• Each index number corresponding to a particular
slot
2
17
5
43
23
12
0
1
2
3
4
5
index numbers
Boundary Errors
• Be careful
• If a list has 10 values the index goes 0 to 9
• If you try and access with an index of 10 the
machine gives you a boundary error,
• You are out of “bounds”
Referring to individual slots
•
•
•
•
We use the name of the list
We use a left square brace [
We use an index number
We use a right square brace ]
• The index number must be an integer
Example: Array of temperature called temp
________
| 80 |
|
79 |
|___81__|
|___78__|
|___77__|
|___78__|
|___80__|
|_______|
|_______|
|_______|
Example:
• Print the 5th slot as stored
• Then store a 55 in the 5th slot
• Slot 5 has an index of 4
-----------------------------temp = [80,79,81,78,77,78,80]
print("5th slot = ", temp[4])
temp [4] = 55
print("Changed 5th slot = ", temp[4])
• -------------------------------------------5th slot = 77
Changed 5th slot = 55
11
Suppose a list of 6 temperatures
• I can print the first element
print(temp[0])
• I can print the second element
print (temp[1])
• How can I print all these elements?
ANSWER - Loop
temp = [80,79,81,78,77,78,80]
print("5th slot = ", temp[4])
temp [4] = 55
print("Changed 5th slot = ", temp[4])
for i in range(6):
print (" the element in the ", i, " slot = ", temp[i])
print("done")
Appending elements
• Create an empty list:
friends = []
• Append elements to end of list
friends.append(“Barb”)
friends.append(“Chris”)
etc.
Look at code
friends=[]
friends.append("Barb")
friends.append("John")
friends.append("Chris")
friends.append("Tom")
friends.append("Paul")
friends.append("Peter")
friends.append("Ron")
friends.append("Richard ")
for i in range (len(friends)):
print ("The name in the ", i , " slot = ", friends[i])
Inserting into the list
• To Insert an item after the 1st element
friends.insert(1, "Cindy")
for i in range (len(friends)):
print ("The name in the ", i , " slot = ", friends[i])