Cool Computer Science Thing of the Day
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]))
- Creating a list using the similar syntax as index and slice, don’t confuse them
- When concatenating lists, both operands must be lists
To add using concatentation, added item must be list
a_list = a_list + [0]