Overview
Teaching: 15 min
Exercises: 10 minQuestions
How can I store multiple values?
Objectives
Explain why programs need collections of values.
Write programs that create flat lists, index them, slice them, and modify them through assignment and method calls.
cingulate
,
limbic
, etc.[...]
.,
.len
to find out how many values are in a list.roi_volumes = [2.73,145.3,12.7,16.2, 27.6]
# Volume of ROIs :
roi_volumes
[2.73,145.3,12.7,16.2, 27.6]
# length:
len(roi_volumes)
5
# The item with index 0 in the list is :
roi_volumes[0]
2.73
# The item with index 4 in the list is :
roi_volumes[4]
27.6
roi_volumes[0] = 26.5
# Our list is now:
roi_volumes
Our list is now: [26.5,145.3,12.7,16.2, 27.6]
list_name.append
to add items to the end of a list.# Our list is initially:
roi_volumes
[26.5,145.3,12.7,16.2, 27.6]
roi_volumes.append(14.2)
roi_volumes.append(140)
# Our list has now become:
roi_volumes
[26.5,145.3,12.7,16.2, 27.6,14.2,140]
append
is a method of lists.
object_name.method_name
to call methods.
dir
function or by accessing the help for
an object.del
to remove items from a list entirely.del list_name[index]
removes an item from a list and shortens the list.# roi_volumes before removing last item:
roi_volumes
[26.5,145.3,12.7,16.2, 27.6,14.2,140]
del roi_volumes[6]
# roi_volumes after removing last item:
roi_volumes
[26.5,145.3,12.7,16.2, 27.6,14.2]
[]
on its own to represent a list that doesn’t contain any values.
goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']
While this list can be created there are better ways of representing this type of information.
label_for_roi = 'cortex_left'
# The character indexed by 0:
label_for_roi[0]
# The character indexed by 3:
c
label_for_roi[3]
t
label_for_roi[0] = 'C'
TypeError: 'str' object does not support item assignment
IndexError
if we attempt to access a value that doesn’t exist.
# The character indexed by 99 is:
label_for_roi[99]
IndexError: string index out of range
Fill in the Blanks
Fill in the blanks so that the program below produces the output shown.
values = [] values.____(1) values.____(3) values.____(5) print('first time:', values) values = values[____] print('second time:', values)
first time: [1, 3, 5] second time: [3, 5]
Solution
values = [] values.append(1) values.append(3) values.append(5) print('first time:', values) values = values[1:3] print('second time:', values)
How Large is a Slice?
If ‘low’ and ‘high’ are both non-negative integers, how long is the list
values[low:high]
?Solution
high-low
From Strings to Lists and Back
Given this:
print('string to list:', list('ADHD')) print('list to string:', ''.join(['c', 'n', 's']))
string to list: ['A', 'D', 'H', 'D'] list to string: 'cns'
- Explain in simple terms what
list('some string')
does.- What does
'-'.join(['x', 'y'])
generate?
Working With the End
What does the following program print?
roi_label = 'hippocampus' print(roi_label[-1])
- How does Python interpret a negative index?
- If a list or string has N elements, what is the most negative index that can safely be used with it, and what location does that index represent?
- If
values
is a list, what doesdel values[-1]
do?- How can you display all elements but the last one without changing
values
? (Hint: you will need to combine slicing and negative indexing.)Solution
1: It retrieves elements by stepping backwards through the string. 2: -N. This location is the first element in the list. 3: It deletes the last element in the list. 4: values[0:-1]
Stepping Through a List
What does the following program print?
roi_label = 'hippocampus' print(roi_label[::2]) print(roi_label[::-1])
- If we write a slice as
low:high:stride
, what doesstride
do?- What expression would select every other element, starting from the second?
Solution
hpoaps supmacoppih
1: stride is the step to go through the list
The answer to question 2 is:
listobject[1::2]
Slice Bounds
What does the following program print?
roi_label = 'hippocampus' print(roi_label[0:20]) print(roi_label[-1:3])
Solution
hippocampus
Sort and Sorted
roi_label_as_list = list(roi_label)
In simple terms, explain the difference between
sorted(roi_label_as_list)
androi_label_as_list.sort()
.
Copying (or Not)
What do these two programs print? In simple terms, explain the difference between
new = old
andnew = old[:]
. For more information read about deep copy vs shallow copy# Program A old = list('Brain') new = old # simple assignment new[0] = 'D' print('new is', new, 'and old is', old)
# Program B old = list('Brain') new = old[:] # assigning a slice new[0] = 'D' print('new is', new, 'and old is', old)
Key Points
A list stores many values in a single structure.
Use an item’s index to fetch it from a list.
Lists’ values can be replaced by assigning to them.
Appending items to a list lengthens it.
Use
del
to remove items from a list entirely.The empty list contains no values.
Lists may contain values of different types.
Character strings can be indexed like lists.
Character strings are immutable.
Indexing beyond the end of the collection is an error.