Python: Lists

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

first method for iterating over a list

Useful to loop through the list, but it's not possible to modify the list this way. for item in list: print item

2nd method for iterating over lists, using indexes.

for i in range(len(list)): print list[i] uses indexes to loop through the list, making it possible to also modify the list if needed.

'For' loop syntax when used with a list

for variable in list_name: # Do stuff! A variable name follows the for keyword; it will be assigned the value of each list item in turn. in list_name designates list_name as the list the loop will work on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.

You can also use a for loop on a dictionary to loop through its keys with this convention:

# A simple dictionary d = {"foo" : "bar"} for key in d: print d[key] # prints "bar" NOTE: The dictionaries are unordered, meaning, you won't get the keys in any particular order

Some examples of adding keys with strings as values

# Adds a key to the dictionary 'inventory' called 'pocket' and contains a list of three strings inventory['pocket'] = ['seashell','strange berry','lint'] # Sorts the key 'backpack' inventory['backpack'].sort() # goes into the back pack key and removes dagger inventory['backpack'].remove('dagger') # Adds 50 to the gold key inventory['gold']=500 +50

What is a list?

A datatype you can use to store a collection of different pieces of information as a sequence under a single variable name.

Definition: Dictionary

A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces, like so: d = {'key1' : 1, 'key2' : 2, 'key3' : 3} The above dictionary is called 'd' and contains 3 key-value pairs Uses for dictionaries: Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail address with a username).

The length len() of a dictionary is the number of _____

Key-Value pairs it has

_____ allows you to access a small part of a list. Uses this convention

List Slicing list_name[a:b] starting with the index a and ending before the index b.

In Python, Lists are _____

Mutable

Lists have a method called .remove(VALUE) which will

Remove the first instance of the value passed to it. For example: beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart") print beatles >> ["john","paul","george","ringo"]

What is the range() function for??

The Python range() function is just a shortcut for generating a list, so you can use ranges in all the same places you can use lists. range(6) # => [0,1,2,3,4,5] range(1,6) # => [1,2,3,4,5] range(1,6,3) # => [1,4] The range function has three different versions: range(stop) range(start, stop) range(start, stop, step) In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step. If omitted, start defaults to zero and step defaults to one.

How to create a list from a string

animals = "catdogfrog" cat = animals[0:3] # The first three characters of animals dog = animals[3:6] # The fourth through sixth characters frog =animals[6:10] # From the seventh character to the end

How to replace an index,

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index =animals.index('duck') animals.insert(duck_index,'cobra') Output: ['aardvark', 'badger', 'cobra', 'emu', 'fennec fox'] reasoning:

List function has another built in function called _____ which allows you to add items to a list using this convention

append() list_name.append()

The _____ command allows us to remove items from a dictionary. convention -

del del dict_name[key_name] will remove the key key_name and its associated value from the dictionary.

For a list n, what does the del(n[index]) do?

del(n[index]) is like .pop in that it will remove the item at the given index, but it won't return it: del(n[1]) # Doesn't return anything print n # prints [1, 5]

A new value can be associated with a key by assigning a value to the key using this convention

dict_name[key] = new_value

Dictionaries are also mutable, and follow this convention:

dict_name[new_key] = new_value

You can search through a list with this function _____

index() For instance my_list.index("dog") will return the first index that contains the string "dog". An error will occur if there is no such item.

Using the _____ function, we can add to the middle of the list

insert() my_list.insert(4,"cat") adds the item "cat" at index 4 of my_list, and moves the item previously at index 4 and all items following it to the next index (that is, they all get bumped towards the end by one).

This function tells you how many items are in a list, and uses this convention

len() list_length = len(list_name)

items in lists are indexed, and follow this convention, and start at _____ You can access a particular index by doing this:

list_name = [0, 1, 2, ...] list_name[index]

What is the convention of assigning items to a list?

list_name = [item_1, item_2] with the items in between brackets. A list can also be empty: empty_list = [].

Another new function: sort()

my_list.sort() will sort the items in my_list in increasing numerical/alphabetical order. does not return a new list; instead, your existing my_list is sorted in place (the sorted version replaces the unsorted version).

For a list n, what does the pop(index) do when in this case: n.pop(index)

n.pop(index) will remove the item at index from the list and return it to you: n = [1, 3, 5] n.pop(1) # Returns 3 (the item at index 1) print n # prints [1, 5]

For a list n, what does the remove(item) function do?

n.remove(item) will remove the actual item if it finds it: n = [1, 3, 5] n.remove(1) # Removes 1 from the list, # NOT the item at index 1 print n # prints [3, 5]

What are the three versions of the range function?

range(6) # => [0,1,2,3,4,5] range(1,6) # => [1,2,3,4,5] range(1,6,3) # => [1,4] range(stop) range(start, stop) range(start, stop, step) In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step. If omitted, start defaults to zero and step defaults to one.

Example of a dictionary

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['Puffin'] # Prints Puffin's room number print residents['Sloth'] print residents['Burmese Python'] Output: 104 105 106 Accessing dictionary values by key is just like accessing list values by index

Good example of a for loop, populating an empty list

start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for num in start_list: x= num**2 square_list.append(x) square_list.sort() print square_list

Define Mutable

they can be changed.

Warning about list slicing

when you are doing list slicing, the last item listed will actually be b-1 in the index. for example: my_list = [0, 1, 2, 3] my_slice = my_list[1:3] print my_list # Prints [0, 1, 2, 3] print my_slice # Prints [1, 2]


Kaugnay na mga set ng pag-aaral

Advanced Automotive System 2 Final Review Questions

View Set

Driver's Ed. AAA How to Drive Ch. 3

View Set

Econ Final Exam and Cumulative Quizzes

View Set

Chapter 17 endocrine system part two

View Set

Respiratory: CO2 Transport, CO, and Cyanide

View Set