Lab 2-Part 2: Lists
Lab 2-Part 2: Lists
Lists:
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero. You can
remove values from the list, and add new values to the end. Example: Your many cats' names.
Compound data types, used to group together other values. The most versatile is the list, which can
be written as a list of comma-separated values (items) between square brackets. List items need not
all have the same type.
Compound datatype:
>>> a = ['spam', 'eggs', 100, 1234]
>>> a[1:-1] #start at element at index 1, end before last element
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
>>> a= ['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
Length of list:
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4
Nested lists:
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
Functions of lists:
list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] =
L.
list.insert(i, x): Insert an item at a given position. The first argument is the index of the
element before which to insert, so a.insert(0, x) inserts at the front of the list, and
a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x): Remove the first item from the list whose value is x. It is an error if there is
no such item.
list.pop(i): Remove the item at the given position in the list, and return it. If no index is specified,
a.pop() removes and returns the last item in the list.
list.count(x): Return the number of times x appears in the list.
list.sort(): Sort the items of the list, in place.
list.reverse(): Reverse the elements of the list, in place.
Tuples:
Tuples are just like lists, but you can't change their values. Again, each value is numbered starting
from zero, for easy reference. Example: the names of the months of the year.
Index Value
0 January
1 February
2 March
3 April
4 May
5 June
6 July
7 August
8 September
9 October
10 November
11 December
We can have easy membership tests in Tuples using the keyword in.
>>> 'December' in months # fast membership testing
True
Sets:
A set is an unordered collection with no duplicate elements. Basic uses include membership testing
and eliminating duplicate entries. Set objects also support mathematical operations like union,
intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to
use set(), not {}; the latter creates an empty dictionary.
Example 1:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
{'banana', 'orange', 'pear', 'apple' }
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
Example 2:
>>> # Demonstrate set operations on unique letters from two words
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
Dictionaries:
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an
'index' of words, and for each of them a definition.
In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't
numbered - they aren't in any specific order, either - the key does the same thing. You can add,
remove, and modify the values in dictionaries. Example: telephone book.
The main operations on a dictionary are storing a value with some key and extracting the value given
the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in
use, the old value associated with that key is forgotten. It is an error to extract a value using a non-
existent key.
Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in
arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). To check whether a single key
is in the dictionary, use the in keyword.
At one time, only one value may be stored against a particular key. Storing a new value for an
existing key overwrites its old value. If you need to store more than one value for a particular key, it
can be done by storing a list as the value for a key
phonebook = {'ali':8806336, 'omer':6784346,'shoaib':7658344,
'saad':1122345}
#Add the person '' to the phonebook:
phonebook['waqas'] = 1234567
print("Original Phonebook")
print(phonebook)
# Remove the person 'shoaib' from the phonebook:
del phonebook['shoaib']
print("'shoaib' deleted from phonebook")
print(phonebook)
phonebook = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Louis Lane':1122345}
print("New phonebook")
print(phonebook)
#Add the person 'Gingerbread Man' to the phonebook:
phonebook['Gingerbread Man'] = 1234567
list(phonebook.keys())
sorted(phonebook.keys())
print( 'waqas' in phonebook)
Generators:
Generators are very easy to implement, but a bit difficult to understand. Generators are used to
create iterators, but with a different approach. Generators are simple functions which return an
iteratable set of items, one at a time, in a special way.
When an iteration over a set of item starts using the for statement, the generator is run. Once the
generator's function code reaches a "yield" statement, the generator yields its execution back to the
for loop, returning a new value from the set. The generator function can generate as many values
(possibly infinite) as it wants, yielding each one in its turn.
Here is a simple example of a generator function which returns 7 random integers:
import random
def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1,15)
for random_number in lottery():
print ("And the next number is... %d!" % random_number)
2. Create list of Fibonacci numbers after calculating Fibonacci series up to the number n which you
will pass to a function as an argument. The number n must be input by the user.
They are calculated using the following formula: The first two numbers of the series
is always equal to 1, and each consecutive number returned is the sum of the last two
numbers. Hint: Can you use only two variables in the generator function?
a = 1
b = 2
a, b = b, a
will simultaneously switch the values of a and b.
The first number in the series should be 1. (The output will start like 1,1,2,3,5,8, …)
3. Write a program that lets the user enter some English text, then converts the text to
Pig-Latin. To review, Pig-Latin takes the first letter of a word, puts it at the end, and
appends “ay”. The only exception is if the first letter is a vowel, in which case we
keep it as it is and append “hay” to the end. For example: “hello” -> “ellohay”, and
“image” -> “imagehay”
It will be useful to define a list or tuple at the top called VOWELS. This way, you can
check if a letter x is a vowel with the expression x in VOWELS.
It’s tricky for us to deal with punctuation and numbers with what we know so far, so
instead, ask the user to enter only words and spaces. You can convert their input from
a string to a list of strings by calling split on the string:
“My name is John Smith”.split(“ ”) -> [“My”, “name”, “is”, “John”, “Smith”]
4. Add the following functions to the s_calc you created in Task 2A-1 and Task2A-2.
a. sin(x)
b. cos(x)
c. tan(x)
d. sqrt