Topic 1 - List and list slicing Flashcards
What is a list in Python?
A list contains multiple values in an ordered sequence.
The values in lists are sometimes called _____
Items
Lists use what kind of brackets?
Square brackets [ ]
Provide an example of three values which are assigned to one variable.
pets = [ ‘dog’, ‘cat’ , ‘rabbit’ ]
How do you access specific values in a list?
You use the integer index value.
pets[0]
»»dog
True or False
- Lists can contain lists
True
What integer value would be used to access the value ‘bat’
pets = [ [‘cat’, ‘bat’], [10,20,20] ]
pets[0] [1]
What is a negative index used for in lists?
A negative index is used to start at the end of a list and work backwards.
pets = [‘rat’, ‘cat’, ‘dog’, ‘elephant’]
What value would this statement produce?
pets[-2]
dog
How many indexes does a slice have and what do they represent?
A slice has TWO indexes separated by a colon
These indexes represent the start and end index.
pets = [‘rat’, ‘cat’, ‘dog’, ‘elephant’]
What values would this slice produce?
pets [1:3}
‘cat’, ‘dog’
Explanation:
The slice would begin at index 1, go to index 3, BUT, not include index 3.
How can you update the value in a list?
You can assign a new value in a list by referencing the index value.
Example:
pets[0] = ‘bat’
How can you update multiple values in a list?
You use a slice to specify the starting index and the end index.
pets[1:3] = [‘rat’, ‘cat’, ‘dog’, ]
What does this slice shortcut do?
pets[:3] = [‘rat’, ‘cat’, ‘dog’, ]
Leaving a blank number is the same as entering ‘0’.
This tells python to start at the first index.
How would you delete the value of ‘rat’ from the list
pets = [‘rat’, ‘cat’, ‘dog’, ‘elephant’]
del pets[0]