Chapter 7 Flashcards
What is a sequence?
An Object that contains multiple items of data
What is a list?
An object that contains multiple data items
EX: even_numbers = [2, 4, 6, 8, 10]
info = [‘Alicia’, 27, 1550.87}
What is an element?
Each object that is stored in a list
How do you display an entire list?
Use the print function:
numbers = [5, 10, 15, 20]
print(numbers)
How would you convert certain objects to lists using range:
numbers = list(range(5))
- The range function is called with 5 passed as an argument. The function returns an iterable containing the values 0, 1, 2, 3, 4.
- The iterable is passed as an argument to the list() function. – -The list() function returns the list [0, 1, 2, 3, 4].
- The list [0, 1, 2, 3, 4] is assigned to the numbers variable.
What is a repetition operator?
when the operand on the left side of the * symbol is a sequence (such as a list) and the operand on the right side is an integer, EX: 1 >>> numbers = [1, 2, 3] * 3 [Enter] 2 >>> print(numbers) [Enter] 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] 4 >>>
How do you access a list with a for loop?
numbers = [1, 2, 3, 4]
for num in numbers:
print(num)
The numbers variable references a list with four elements, so this loop will iterate four times. The first time the loop iterates, the num variable will reference the value 1, the second time the loop iterates, the num variable will reference the value 2, and so forth.
-num variable value has no effect on the output
What is an index ?
Each element in a list has an index that specifies its position in the list. Indexing starts at 0, sothe index of the first element is 0
print(my_list[0], my_list[1], my_list[2], my_list[3])
EX #2:
index = 0
while index < 4:
print(my_list[index])
index += 1
What is an indexError exception?
raised if you use an invalid index with a list.
What is the len function in python?
returns the length of a sequence, such as a list.
EX: my_list = [10, 20, 30, 40]
size = len(my_list)
How do you use a len and range function to get the indexes in a list?
1 names = ['Jenny', 'Kelly', 'Chloe', 'Aubrey'] 2 for index in range(len(names)): 3 print(names[index])
What does mutable mean?
Lists in python can be changed EX: Line 3 in this code rewrites an index: 1 numbers = [1, 2, 3, 4, 5] 2 print(numbers) 3 numbers[0] = 99 4 print(numbers)
How do you concatenate a list?
Use the + operator: list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list3 = list1 + list2 OR use += to concatenate one list to the other list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list1 += list2
What is a slice?
A span of items that are taken from a sequence
EX: list_name[start : end]
days = [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’,
‘Thursday’, ‘Friday’, ‘Saturday’]
mid_days = days[2:5]
[‘Tuesday’, ‘Wednesday’, ‘Thursday’]
(Does not include end but includes start)
How do you slice a list with a step value?
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
»_space;> print(numbers[1:8:2]) [Enter]
[2, 4, 6, 8]
-Step value of 2 to get every other item form the list