Upload
dulcie-felicia-hardy
View
229
Download
1
Embed Size (px)
Citation preview
COMPUTER SCIENCE
FEBRUARY 2011
Lists in Python
Introduction to Lists
Lists (aka arrays): an ordered set of elements A compound data type, like strings
Think of a CD box The box : list CDs : elements Fixed size CDs stored in order
Why Use Lists?
Faster than defining variables for each element
Can perform operations on each element Think of Robot game: had to copy/paste code for each
item
More flexible Easy to add/remove elements
Can pass an entire list to a function
Lists in Python
Most languages: elements must be of same data type
Python: can mix data types Integers, floats (decimals) , string, even other lists.
Creating Lists & Getting Length
Create by specifying elementsint_list=[202,10, 54, 23]
print(int_list)
..or create an empty listempty_list=[]
print(empty_list)
Use len() to return the number of elementsprint len(int_list)
print len(empty_list)
Accessing elements
Access individual elements using bracketsFirst element is 0.
int_list=[202,10, 54, 23]
int_list[1]
int_list[3]
Access from end using negative indicesint_list[-1]
int_list[-3]
Specifying slices
Access a slice (sub-list) using rangesIncludes first element in range, excludes last in
range int_list=[202,10, 54, 23]
int_list[0:1]
int_list[2:3]
int _list[0:0]
Note: this is different from int _list[0]
Omit values to get start or end of listint_list[:2]
int_list[2:]
Using a while loopUsing a while loop Using for value in listUsing for value in list
int_list=[202,10, 54, 23]
index=0
sum_values=0
while (index<len(int_list)):
value = int_list[index]
sum_values+=value
index+=1
for value in int_list:
sum_values+=value
Iterate through lists
Manipulating lists
Lists are mutable (changeable), unlike strings.Replace a single element
int_list=[202,10, 54, 23]
int_list[1]=11
Replace a sliceint_list[1:3]=[12,99]
Delete by replacing a slice with an empty listint_list[1:3]=[]
Add an element by ‘squeezing’ it in int_list[4:4]=100
int_list[ ] = 20
Nested Lists
Lists can contain other listsint_list=[202,10, 54, 23]
mixed_list=[“a”, int_list, 23]
List length is number of ‘top level’ elementsprint len(mixed_list)