Chapter 7 Flashcards
numbers = [1, 2, 3, 4, 5]
numbers[2] = 99
print(numbers)
[1, 2, 99, 4, 5]
numbers = list(range(3))
print(numbers)
[0, 1, 2]
numbers = [10] * 5
print(numbers)
[10, 10, 10, 10, 10]
numbers = list(range(1, 10, 2))
for n in numbers:
print(n)
1
3
5
7
9
numbers = [1, 2, 3, 4, 5]
print(numbers[−2])
4
How do you find the number of elements in a list?
Use the build-in len function
numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
numbers3 = numbers1 + numbers2
print(numbers1)
print(numbers2)
print(numbers3)
[1, 2, 3]
[10, 20, 30]
[1, 2, 3, 10, 20, 30]
numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
numbers2 += numbers1
print(numbers1)
print(numbers2)
[1, 2, 3]
[10, 20, 30, 1, 2, 3]
numbers = [1, 2, 3, 4, 5]
my_list = numbers[1:3]
print(my_list)
[2, 3]
numbers = [1, 2, 3, 4, 5]
my_list = numbers[1:]
print(my_list)
[2, 3, 4, 5] ? [2, 3]
numbers = [1, 2, 3, 4, 5]
my_list = numbers[:1]
print(my_list)
[1]
numbers = [1, 2, 3, 4, 5]
my_list = numbers[:]
print(my_list)
[1, 2, 3, 4, 5]
numbers = [1, 2, 3, 4, 5]
my_list = numbers[−3:]
print(my_list)
[3, 4, 5]
names = [‘Jim’, ‘Jill’, ‘John’, ‘Jasmine’]
if ‘Jasmine’ not in names:
print(‘Cannot find Jasmine.’)
else:
print(“Jasmine’s family:”)
print(names)
Jasmine’s family:
[‘Jim’, ‘Jill’, ‘John’, ‘Jasmine’]
What is the difference between calling a list’s remove method and using the del statement to remove an element?
The remove method searches for and removes an element containing a specific value.
The del statement removes an element at a specific index.
How do you find the lowest and highest values in a list?
You can use the built-in min and max functions.
How do you find the lowest and highest values in a list?
names = []
Which of the following statements would you use to add the string ‘Wendy’ to the list at index 0? Why would you select this statement instead of the other?
a. names[0] = ‘Wendy’
b. names.append(‘Wendy’)
You would use statement b, names.append(‘Wendy’).
This is because element 0 does not exist.
If you try to use statement a, an error will occur.