Lecture 26 + HW:

posted Mar 11, 2013, 6:15 AM by Samuel Konstantinovich   [ updated Mar 15, 2013, 5:34 AM ]
Goal: To use Lists

RECAP: (New Stuff from last week)
Remember you should know some string methods such as:

Remember you should know the operation in,  like   a in b

What does this function do?

def myst(c):

    return c in 'aeiou'

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

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


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:]


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:
LLama = [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]
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'
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'
x [ - len(x)]  is 'a'

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!

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

#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.

Lists don't have the same methods as strings!
Read the list documentation here and play around with the commands to figure them out: