2014-03-20 + HW

posted Mar 21, 2014, 5:47 AM by Samuel Konstantinovich   [ updated Mar 21, 2014, 5:47 AM ]
Goal: To use Lists

RECAP: (New Stuff from homework)
Remember you should know some string methods such as:
find
replace
strip
upper
lower
etc.

You should know the operation in,  like   a in b

DO NOW: (ON PAPER!)

We can define a list as follows:
>>> L=[1 ,2 ,3 ,44, 9, -3]
The value is shown on the shell:
>>> print L
[1, 2, 3, 44, 9, -3]

What are the values of the following expressions? (Lists can be indexed and sliced just like strings.)
1. L[0]
2. L[3]
3. L[2:4]
4. L[4:]

5.What does this function do? What is a better name for it?

def myst(c):

    return c in 'aeiou'


Methods vs Functions
METHOD is different from a function because it is used in the format:
variable.methodName(...)    #some with parameters some without
"blah".upper()
math.sqrt(9)  #after you import math

FUNCTION is used without the variable. part:
foo(...)
myUpper(s)      #if you write an upper function, it is not a method


CLASSWORK:

Unlike a string, which only contains characters, Lists can contain any data types if you want, and can mix and match types in the same list:
L = [1,'a',3.9,'fishsticks']

List and String indexing    V[a:b:c]
a is the starting point (inclusive)
b is the ending point (exclusive)
c is the step amount , or how many indices you count by.

So L[::2] is every 2nd element staring at the begining [ 1, 3.9 ]
6. L[1::2] is [ 'a' ,'fishsticks' ]
7. "Betty"[::2]
8. "Betty"[1::3]
9. "abcdefghijklmnop"[3:10:2]
10. "abcdefghijklmnop"[3:11:2]

Negative Index Values:
x = 'abefg'
x [ len(x) - 1]  is 'g'
x [ len(x) - 2]  is 'f'
etc...
x [ len(x) - len(x)]  is 'a'

BUT you can index them using negative numbers the same way! (notice the same as before without len(x) )
x [ - 1]  is 'g'
x [ - 2]  is 'f'
etc...
x [ - len(x)]  is 'a'

Remember:
positive index values go from 0 to len-1.
negative index values go from -1 to -len. (since you cannot use 0)

Negative works with slices too!
>>> x='0123456789'

>>> x[::-1]   #a negative step can be used!
'9876543210'

>>> x[-3:-1]   #starting with the 7, up to but not including the last character
'78'


#THIS IS FYI, but not required:
>>> x[-3:-1:-1] #same range as before with a negative step doesn't work! Because the indices are reversed!
''
>>> x[-1:-3:-1] #you now start with the new left-most index, which is the -1.
'98'

Finally This is required:

Some methods require knowledge of both strings and lists.

Classwork was showing examples of:
string.split()
string.join()


HOMEWORK!
Lists don't have the same methods as strings!
Read the list documentation here and play around with the commands to figure them out: 
http://docs.python.org/2/tutorial/datastructures.html
What are 5 differences between strings and lists?
Print out some examples AND describe what the examples show.
Print your heading on the top of the page or it will not be counted.
Comments