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

Lab 7

Uploaded by

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

Lab 7

Uploaded by

Hafiz Muhammad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Practical 7

Implementing Tuple, List and Understanding Aliasing, Cloning

Objective:

● To have basic understanding of Tuples and Lists in Python.


● To understand the concepts of Aliasing and Cloning in Python.

Tools/Software Requirement

● Python 3.0

Theory
Python offers a range of compound data types often referred to as sequences. List is one of the most
frequently used and very versatile data type used in Python. In Python programming, a list is created by
placing all the items (elements) inside a square bracket [ ], separated by commas. It can have any number
of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4. Trying to access an element other that this will raise an IndexError.
The index must be an integer. We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])

# Output: o
print(my_list[2])

# Output: e
print(my_list[4])
# Error! Only integer can be used for indexing
# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a
print(n_list[0][1])

# Output: 5
print(n_list[1][3])

Output:

Negative Indexing:
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second
last item and so on.
my_list = ['p','r','o','b','e']

# Output: e
print(my_list[-1])

# Output: p
print(my_list[-5])
Output:
e
p

In the above example of list, the indexes and negative indexes for the sequence ['p','r','o','b','e'] is in below
sequence
Slicing of List:
We can access a range of items in a list by using the slicing operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

Output:

Slicing can be best visualized by considering the index to be between the elements as shown below. So if
we want to access a range, we need two indices that will slice that portion from the list.

Adding or Changing List Elements:


List are mutable, meaning, their elements can be changed unlike string or tuple. we can use
assignment operator (=) to change an item or a range of items.
# mistake values
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

# Output: [1, 4, 6, 8]
print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

# Output: [1, 3, 5, 7]
print(odd)

Output:
We can add one item to a list using append() method or add several items using extend() method.
odd = [1, 3, 5]

odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)

We can also use + operator to combine two lists. This is also called concatenation. The * operator repeats
a list for the given number of times.
odd = [1, 3, 5]

# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
#Output: ["re", "re", "re"]
print(["re"] * 3)
Furthermore, we can insert one item at a desired location by using the insert() method or insert multiple
items by squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)

# Output: [1, 3, 9]
print(odd)

odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
my_list = ['p','r','o','b','l','e','m']

# delete one item


del my_list[2]

# Output: ['p', 'r', 'b', 'l', 'e', 'm']


print(my_list)

# delete multiple items


del my_list[1:5]

# Output: ['p', 'm']


print(my_list)

# delete entire list


del my_list
# Error: List not defined
print(my_list)

We can use remove() method to remove the given item or pop() method to remove an item at the
given index. The pop() method removes and returns the last item if index is not provided. This helps us
implement lists as stacks (first in, last out data structure). We can also use the clear() method to empty
a list.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

my_list.clear()

# Output: []
print(my_list)

we can also delete items in a list by assigning an empty list to a slice of elements.

>>> my_list = ['p','r','o','b','l','e','m']


>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

List Methods

append() Add an element to the end of the list


extend() Add all elements of a list to the another list
insert() Insert an item at the defined index
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
len() Finds the length/size of the list
index() Returns the index of the first matched item
count() Returns the count of number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a shallow copy of the list
my_list = [3, 8, 1, 6, 0, 8, 4]

# Output: 1
print(my_list.index(8))

# Output: 2
print(my_list.count(8))

my_list.sort()

# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)

my_list.reverse()

# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)

#Output: length of the list is: 7


print(“length of the list is: “, len(my_list))

Tuple:
A tuple in python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas, in a list, elements can be changed. A tuple is
created by placing all the items (elements) inside parenthesis ( ), separated by commas. The
parenthesis are optional, however, it is a good practice to use them. A tuple have any number of item
and they may be of different types (integer, float, list, string, etc.).
Syntactically, a tuple is a comma-separated list of values:

>>> t = 'a', 'b', 'c', 'd', 'e'


>>> t = ('a', 'b', 'c', 'd', 'e')

my_tuple = (1, 2, 3)
print(my_tuple)

#Output: (1, 2, 3)

To create a tuple with a single element, you have to include the final comma:

>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>

Without the comma Python treats ('a') as an expression with a string in parentheses that evaluates to a
string:

>>> t2 = ('a')
>>> type(t2)
<type 'str'>
Another way to construct a tuple is the built-in function tuple. With no argument, it creates an
empty tuple:

>>> t = tuple()
>>> print t

Output: ()

If the argument is a sequence (string, list or tuple), the result of the call to tuple is a tuple with
the elements of the sequence:
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')

Because tuple is the name of a constructor, you should avoid using it as a variable name.
Most list operators also work on tuples. The bracket operator indexes an element:

>>> t = ('a', 'b', 'c', 'd', 'e')


>>> print t[0]
Output: 'a'

the slice operator selects a range of elements.


>>> print t[1:3]
Output: ('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:

>>> t[0] = 'A'


TypeError: object doesn't support item assignment

You can’t modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> print t
Output: ('A', 'b', 'c', 'd', 'e')

Lab Tasks:

1. Make this list, Names = [‘Ali’, ‘Ahsan’, ‘Ahmed’, ‘Zubair’]. Print list and then overwrite each
element of this list by asking the user for input. Make sure the first three members of the list
should be uppercased and print again. Find the name at index 2 using negative indexing.
Code:

Output:
2. Create two lists; each contains marks of four subjects Concatenate them and print the resulting
list. Then slice them to recover the original lists and print them too.

Code:

Output:
3. Make a list of ten numbers and find the following and print.
i. The length of list
ii. Max number from the list
iii. Min number from list
iv. Difference between the max and min
v. Sum of list.
vi. Average of the list.
vii. Sort the array.
viii. Find out the index of max number and delete it

Code:

Output:
4. Write a program to implement Tuples.
PSEUDO CODE:
● Start
● First define the functions for tuples.
● Use for statement to check the tuples.
● Print the tuples.
● Increment the numbers and words.
● Get the maximum and minimum values from the numbers.
● Return the function
● Use assignments
● Call the function.
● End
Code:

Output:
Evaluation Criteria:

Un- Developing Satisfactory Good Exemplary Marks


satisfactory (2) (3) (4) (5)
(0-1)
Does not Completed
comply with less than 75%
Completed at Completed
requirements of the Completed
least 75% of between 80-
(does requirements. 100% of
the 99% of the
something requirements.
Organization/ Not delivered requirements. requirements.
other than Code appears
Structure on time or
requirements). Delivered on Code lacks finished and
not in correct
time, and in some minor organized
Information is format (disk,
correct structural properly
presented in a email,
format. continuity.
very mundane Canvas,
way printout etc.)

Unclear OR
Poorly States explicit
Respective inaccurate
Correct logic written results of a
Code and results due to
but produces program with program in
Results and result does minor
no result due faulty logic accordance
Conclusion not programming
to an error in and syntax, with the
complement logic
the code producing programming
each other negligence or
wrong result. logic
syntax error.

Lab Instructor: Dr. Abdullah Waqas/Lab Engr. Wahaj Rafique Total

You might also like