Pre-registration and Computer Science
- At the end of this course you will know everything you need to write any program you want.
- But there is there are things to can learn to make programming easier.
- CPSC170 Fundamentals of Computer Science
- Learn object oriented programming to make writing programs easier
- For majors and minors
Reading Questions
Quiz
Lists and Types
- Lists, like strings, are collections
- Strings are a collection of characters
- Lists are a collection of anything you want
- Strings are defined using quotes
- Lists are defined using square brackets
So the following are all valid lists
a_list = [3, 4, 2, 0] a_list = [2.4, 1.0, 9.88] a_list = ['a', 'z', 'e', 'i'] a_list = ["banana", "apple"] a_list = [True, False, True] a_list = []
- The type of each of the elements doesn’t have to be the same
So the following is a valid list
a_list = ["one", 2, 3.0]
Lists can even contain other lists
a_list = [[1, 2], 3]
List Operators
All of the operators we learned for string work for lists
print(a_list[2]) print(len(a_list)) print(a_list[1:3]) print(a_list + [1, 2, 3])
It’s worth noting that when the list contains lists, the len function doesn’t count the items in the sub list
print(len([[1, 2], 3])) # this will print 2
- Creating a list uses a similar syntax as the index and slice operators, don’t confuse them
- When concatenating lists, both operands must be lists
To add using concatentation, added item must be list
a_list = a_lilst + 0 # this will produce an error a_list = a_list + [0] # this will work