Lab Manual 3
Lab Manual 3
What is an Array?
An array is a special variable, which can hold more than one value at a time. If you
have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the values
by referring to an index number.
Example
Modify the value of the first array item:
cars[0] = "Toyota"
x = len(cars)
Note: The length of an array is always one more than the highest array
index.
You can use the for in loop to loop through all the elements of an array.
Example
for x in cars:
print(x)
cars.append("Honda")
Removing Array Elements
You can use the pop() method to remove an element from the array.
Example \
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
cars.remove("Volvo")
Note: The remove() method only removes the first occurrence of the
specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists
can be used instead.
Python List:
The list is a most versatile datatype available in Python which can be written as a
list of commaseparated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between
square brackets. For example −
list2 = [1, 2, 3, 4, 5, 6, 7 ];
list1[0]:
physics
list2[1:5]: [2, 3,
4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with
the append() method. For example −
list = ['physics',
1 cmp(list1, list2)
2
len(list)
Gives the total length of the list.
3
max(list)
Returns item from the list with max value.
4
min(list)
Returns item from the list with min value.
5
list(seq)
Converts a tuple into list.
1 list.append(obj)
2
list.count(obj)
Returns count of how many times obj occurs in list
3
list.extend(seq)
Appends the contents of seq to list
4
list.index(obj)
Returns the lowest index in list that obj appears
5
list.insert(index, obj)
Inserts object obj into list at offset index
6
list.pop(obj=list[-1])
Removes and returns last object or obj from list
7
list.remove(obj)
Removes object obj from list
8
list.reverse()
Reverses objects of list in place
9
list.sort([func])
Sorts objects of list, use compare func if given
Python Tuple:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally
you can put these comma-separated values between parentheses also. For example
−
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and
so on.
tup1[0]: physics
tup2[1:5]: [2, 3,
4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of
tuple elements. You are able to take portions of existing tuples to create new tuples
as the following example demonstrates −
= ('abc', 'xyz');
# tup1[0] = 100;
This produces the following result. Note an exception raised, this is because after
del tup tuple does not exist any more −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols,
i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in
these short examples −
print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;
abc -4.24e+93
(18+6.6j) xyz Value of
x,y:12
1
cmp(tuple1, tuple2)
2
len(tuple)
Gives the total length of the tuple.
3
max(tuple)
Returns item from the tuple with max value.
4
min(tuple)
Returns item from the tuple with min value.
5
tuple(seq)
Converts a list into tuple.
Python Sets:
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.
Example
Create a Set:
Note: Sets are unordered, so the items will appear in a random order.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered
the items has no index.
But you can loop through the set items using a loop, for or ask if a specified value
is present in a set, by using thein keyword.
Example
for x in thisset:
print(x)
Example
thisset = {"apple",
"banana", "cherry"}
print("banana" in
thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
Example
print(thisset)
Example
print(thisset)
To determine how many items a set has, use the len() method.
Example
print(len(thisset)
Remove Item
thisset.remove("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.
Example
thisset = {"apple",
"banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use thepop(), method to remove an item, but this method will
remove item. the last ts are unordered, so you will not know what item that
gets removed.
The return value of the pop() method is the removed item.
Example
Note: Sets are unordered, so when using the pop() method, you will not know which item that
gets removed.
Example
print(thisset)
Example
del thisset
print(thisset)
Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Example
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Exercise:
1. Write a Python script to sort (ascending and descending) a dictionary
by value
2. Write a Python script to check if a given key already exists in a
dictionary. 3. Write a Python script to merge two Python dictionaries
4. Write a Python program to add an item in a tuple.
5. Write a Python program to create a tuple with different data types
6. Write a Python program to sum all the items in a list
7. Write a Python program to get the largest number from a list.
8. Write a Python program to add member(s) in a set.
9. Write a Python program to reverse the order of the items in the array
10. Write a Python program to create an array of 5 integers and display the array
items. Access individual element through indexes.