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 elements int_list=[202,10, 54, 23] print(int_list)..or create an empty list empty_list=[] print(empty_list) Use len() to return the number of elements print len(int_list) print len(empty_list)
Accessing elements Access individual elements using brackets First element is 0. int_list=[202,10, 54, 23] int_list[1] int_list[3] Access from end using negative indices int_list[-1] int_list[-3]
Specifying slices Access a slice (sub-list) using ranges Includes 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 list int_list[:2] int_list[2:]
Using a while loop Using 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 slice int_list[1:3]=[12,99] Delete by replacing a slice with an empty list int_list[1:3]=[] Add an element by ‘squeezing’ it in int_list[4:4]=100 int_list[ ] = 20
Nested Lists Lists can contain other lists int_list=[202,10, 54, 23] mixed_list=[“a”, int_list, 23] List length is number of ‘top level’ elements print len(mixed_list)