BeginnersTutorial:Tutorial/Lesson 4

From jWork.ORG
Jump to: navigation, search


Lesson 4: Lists of things

Variables can also represent complicated objects, such as "lists" A list is just a collection of numbers, strings or any other "objects".

Here is an example:

zoo=["monkey", "python", "rabbit"]

Or you can put a list of numbers:

counts=[1, 25, 100]


You may print such variables using "print" and also check the type as:

zoo=["monkey", "python", "rabbit"]
counts=[1, 25, 100]
print zoo, counts

Run this code. Now you can see the the power of lists - our variable (which is a list) holds a sequence of numbers or strings. In fact, it can even hold several lists:

zoo=["monkey", "python", "rabbit"]
counts=[1, 25, 100]
biglist=[zoo,counts]
print biglist

Ok, how so how do you find a single variable inside a list? Use index. Index is an integer number that shows the position inside the list. "0" always means first position, "1" means second position etc.

Try this:

zoo=["monkey", "python", "rabbit"]
print zoo[1]

Which will print:

python

Note, if you need to access first ellement, use index "0". If you need to access the last ellements, simply use the index "-1".


You can make a mistake by using very large index value, larger than size itself. Therefore, you should know how to find the size of the list. There is a useful function called "len()" that shows the length of the list:

zoo=["monkey", "python", "rabbit"]
length=len(zoo)

If you will print "length", it will show "3".

Lists are flexible, you can put anything in them, including other lists.

zoo = [3, 4, 5, [7, 8], 'cat']
print zoo[3]

and it shows the list [7,8] that sits inside the list "a".

Lists are "mutable", which means you can change their values.

zoo = [3, 4, 5, [7, 8], 'cat']
print zoo[0], zoo[-1]
zoo[-1] = 'dog'
print zoo
3 cat



Tuples

Tuples are immutable; you cannot change their values. This is handy in cases where it is an error to change the value. A tuple is like a list but it is enclosed in parentheses.

zoo = (3, 4, 5, [7, 8], 'cat')
print zoo[0], zoo[-1]
zoo[-1] = 'dog'

Now you cannot assign a new value, like

zoo[0]=1

This will give an error!


Dictionaries

Dictionaries are used to assigne a value to some "key".

Dictionaries are enclosed in curly brackets, and are composed of key:value pairs.

dic = {'name':'benzene', 'A':6.9056, 'B':1211.0}
dic['C'] = 220.79
dic['Trange'] = [-16, 104]
print dic
print dic['Trange']

This will print:

{'A': 6.9056, 'C': 220.79, 'B': 1211.0, 'name': 'benzene', 'Trange': [-16, 104]}
[-16, 104]


You can always pring keys and values as:

print s.keys()
print s.values()