Docsity

Python Lists in CS110: Insertion, Initialization, and Object-Oriented Function Calls - Pro, Study notes of Computer Science

Toggle sidebar
bg1
CS 110: Introduction to Computer Science Spring 2008
Lists
Revisiting Lists in Python
We discussed lists a bit in our discussion on iteration. Let's look
more in-depth at what you can do with lists.
Putting elements in lists
In the preceding notes, we put elements in lists by creating a list
with a single statement:
list=['a','b','c']
You can also modify a list using an index:
list[2]='x'
Python also provides some functions you can call to insert things in
lists:
append
-- appends a new element to the end of a list.
list = [1,2,3]
list.append(4)
print list
[1,2,3,4]
insert -- inserts an element somewhere in the list.
list.insert(2,99) # should put 99 in the 2nd slot.
print list
[1,2,99,3,4]
Initializing Lists
You can initialize lists by assigning a list to the empty list [ ], e.g.,
list=[]
pf3

Partial preview of the text

Download Python Lists in CS110: Insertion, Initialization, and Object-Oriented Function Calls - Pro and more Study notes Computer Science in PDF only on Docsity!

Lists

Revisiting Lists in Python We discussed lists a bit in our discussion on iteration. Let's look more in-depth at what you can do with lists. Putting elements in lists In the preceding notes, we put elements in lists by creating a list with a single statement: list=['a','b','c'] You can also modify a list using an index: list[2]='x' Python also provides some functions you can call to insert things in lists: append -- appends a new element to the end of a list. list = [1,2,3] list.append(4) print list [1,2,3,4] insert -- inserts an element somewhere in the list. list.insert(2,99) # should put 99 in the 2nd slot. print list [1,2,99,3,4] Initializing Lists You can initialize lists by assigning a list to the empty list [ ], e.g., list=[]

Note that you need to initialize a list before calling 'append'-- You can't append to a list that hasn't been initialized either with an empty or non-empty list (e.g., list=[1,2,3] You also cannot access/set an element of a list unless the list already has that element. So the following code will give an error: list=[] list[0]=4 # error list2=[1,2] list2[3]=7 # error Copying and Aliasing The following statement does NOT make a copy of a list: list1=list It creates an alias-- both variables will point at the same contents. Consider the following code: list1=[1,2,3] list2=list1 # *** list2[1]= Both list1 will print as [1,55,3] You can create a copy of a list using a statement like the following: list2=list1[:] If this line replaces *** in the code above, list1 will not be modified when list2 is. The ':' syntax is an example of 'get range' operation of a list. list2=list1[0:1] # returns the first two elements of list1.