0% found this document useful (0 votes)
4 views

Lab Manual 3

The document outlines key concepts in Python, focusing on data structures such as arrays, lists, tuples, and sets. It explains how to create, access, modify, and delete elements within these structures, along with their respective methods and operations. Additionally, it highlights the differences between these data types, emphasizing that lists are versatile while tuples are immutable.

Uploaded by

pajeg11558
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab Manual 3

The document outlines key concepts in Python, focusing on data structures such as arrays, lists, tuples, and sets. It explains how to create, access, modify, and delete elements within these structures, along with their respective methods and operations. Additionally, it highlights the differences between these data types, emphasizing that lists are versatile while tuples are immutable.

Uploaded by

pajeg11558
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Artificial Intelligence

Department of Computer Science


University of Engineering and Technology, Lahore

Class Learning Outcomes


Students will learn about the following concepts in Python
• Arrays
• Lists
• Tuples
• Sets
• Dictionary

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:

car1 = "Ford" car2


= "Volvo" car3 =
"BMW"

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?

The solution is an array!

An array can hold many values under a single name, and you can access the values
by referring to an index number.

Access the Elements of an Array

You refer to an array element by referring to the index number.


Example

Get the value of the first array item:


x = cars[0]

Example
Modify the value of the first array item:

cars[0] = "Toyota"

The Length of an Array


Use the len() method to return the length of an array (the number of elements in an
array).
Example

Return the number of elements in the cars array:

x = len(cars)

Note: The length of an array is always one more than the highest array
index.

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.
Example

Print each item in the cars array:

for x in cars:
print(x)

Adding Array Elements

You can use the append() method to add an element to an array.


Example

Add one more element to the cars array:

cars.append("Honda")
Removing Array Elements

You can use the pop() method to remove an element from the array.
Example \

Delete the second element of the cars array:

cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example

Delete the element that has the value "Volvo":

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

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list


count() Returns the number of elements with the specified value

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.

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list

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 −

list1 = ['physics', 'chemistry',


1997, 2000]; list2 = [1, 2, 3, 4, 5
]; list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.

Accessing Values in Lists


To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −

list1 = ['physics', 'chemistry', 1997, 2000];

list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0]

print "list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result −

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',

'chemistry', 1997, 2000];

print "Value available at

index 2 : " print list[2]

list[2] = 2001; print "New

value available at index 2 :

" print list[2]

Note − append() method is discussed in subsequent


section. When the above code is executed, it produces the
following result −

Value available at index 2 :


1997
New value available at index 2 :
2001

Delete List Elements


To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For
example −

list1 = ['physics', 'chemistry', 1997, 2000]; print list1

del list1[2]; print "After deleting value


at index 2 : " print list1

When the above code is executed, it produces following result −


['physics', 'chemistry', 1997, 2000] After deleting value at index 2
:
['physics', 'chemistry', 2000]
Note − remove() method is discussed in subsequent section.

Basic List Operations


Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in
the prior chapter.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they
do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description

L[2] SPAM! Offsets start at zero

L[-2] Spam Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions & Methods


Python includes the following list functions −
Sr.No. Function with Description

1 cmp(list1, list2)

Compares elements of both lists.

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.

Python includes following list methods


Sr.No. Methods with Description

1 list.append(obj)

Appends object obj to list

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 = ('physics', 'chemistry',


1997, 2000); tup2 = (1, 2, 3, 4, 5
); tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though
there is only one value −

tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and
so on.

Accessing Values in Tuples


To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −

tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0];

print "tup2[1:5]: ", tup2[1:5];


When the above code is executed, it produces the following result −

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 −

tup1 = (12, 34.56); tup2

= ('abc', 'xyz');

# Following action is not valid for tuples

# tup1[0] = 100;

# So let's create a new tuple as follows

tup3 = tup1 + tup2; print


tup3;

When the above code is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −

tup = ('physics', 'chemistry', 1997, 2000);


print tup;
del tup;
print "After deleting tup : ";
print tup;

This produces the following result. Note an exception raised, this is because after
del tup tuple does not exist any more −

('physics', 'chemistry', 1997,


2000) After deleting tup :
Traceback (most recent call
last): File "test.py", line 9, in
<module> print tup;
NameError: name 'tup' is not
defined

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings
in the prior chapter −

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition


3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because tuples are sequences, indexing and slicing work the same way for tuples as
they do for strings. Assuming following input −

L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

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;

When the above code is executed, it produces the following result −

abc -4.24e+93
(18+6.6j) xyz Value of
x,y:12

Built-in Tuple Functions


Python includes the following tuple functions −
Sr.No. Function with Description

1
cmp(tuple1, tuple2)

Compares elements of both tuples.

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:

thisset = {"apple", "banana", "cherry"}


print(thisset)

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

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Example

Check if "banana" is present in the set:

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 one item to a set use the add() method.

To add more than one item to a set use the update() method.

Example

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")

print(thisset)

Example

Add multiple items to a set, using the update() method:

thisset = {"apple", "banana", "cherry"}


thisset.update(["orange", "mango", "grapes"])

print(thisset)

Get the Length of a Set

To determine how many items a set has, use the len() method.
Example

Get the number of items in a set:


thisset = {"apple", "banana", "cherry"}

print(len(thisset)

Remove Item

To remove an item in a set, use the remove(), or the discard() method.


Example

Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example

Remove "banana" by using the discard() method:

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

Remove the last item by using the pop() method:


thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x) print(thisset)

Note: Sets are unordered, so when using the pop() method, you will not know which item that
gets removed.

Example

The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}


thisset.clear()

print(thisset)

Example

The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset
print(thisset)

Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python


dictionaries are written with curly brackets, and they have keys and values.
Example

Create and print a 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

Get the value of the "model" key:

x = thisdict["model"]

There is also a method called get() that will give you the same result:

Example

Get the value of the "model" key:

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.

You might also like