0% found this document useful (0 votes)
23 views43 pages

Updated Week 09

The document discusses lists and tuples in Python. It defines lists and tuples, explains why they are needed, and how to create, access, and modify their elements. Lists are ordered and mutable collections of items while tuples are ordered and immutable. The document covers list/tuple syntax, indexing, slicing, built-in methods and functions to add, remove, sort and manipulate elements in lists and tuples.

Uploaded by

Fardeen Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views43 pages

Updated Week 09

The document discusses lists and tuples in Python. It defines lists and tuples, explains why they are needed, and how to create, access, and modify their elements. Lists are ordered and mutable collections of items while tuples are ordered and immutable. The document covers list/tuple syntax, indexing, slicing, built-in methods and functions to add, remove, sort and manipulate elements in lists and tuples.

Uploaded by

Fardeen Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

List in Python

Computer Science Department, UET Lahore.


Learning Objectives
• Define why do we need Lists in Python.

• Learn about the Mutable and immutable data structures

• Define and implement of Lists

• Define, understand, and implement functions of lists

Computer Science Department, UET Lahore.


Why do we need List? (Why)
By keeping a list, you make sure that your tasks are written
down all in one place so you don't forget anything important
For example, to make a ‘to-do’ list for daily tasks. You prioritize
your tasks while making a list that which tasks are more important
and which are less important.

Computer Science Department, UET Lahore.


Why do we need list in Python?
List is used to store multiple data of the same type
or different type.
It is an ordered set of values enclosed in
a square bracket [].

Computer Science Department, UET Lahore.


Mutable list in Python?
The Values in the list can be modified, that’s why
list it is called mutable.

Computer Science Department, UET Lahore.


Creating a list in Python?
List is creating by placing all the items (elements)
inside a square bracket [], separated by commas.
# Empty lists
my_list = []
# List of integers
my_list = [1,2,3]
# List of Mixed Data Types
my_list = [1, “Hello”, 3.5]

Computer Science Department, UET Lahore.


Index of a list?
my_list = [55,65,75,85,95]

Forward Indexing Elements Backward Indexing

0 55 -5

1 65 -4

2 75 -3

3 85 -2

4 95 -1

Computer Science Department, UET Lahore.


Accessing item from a list?
Use the Index operator [] to access an item in a list.
As Index starts from zero.
So, a list having 5 elements will have index from 0(zero) to 4.

my_list= [1,2,3,4,5]
print(list[2]) #Positive indexing Output
print(list[-2]) #Negative indexing 3
4

Computer Science Department, UET Lahore.


How to change or Update list?
my_list = [55,65,75,85,95]
print(my_list)
Output:
[55,65,75,85,95]

my_list = [55,65,75,85,95]
my_list[1] = 56
print(my_list)
Output:
[55,56,75,85,95]

Computer Science Department, UET Lahore.


List Operators?
▪ Slicing [::] :
▪ Concatenation +
▪ Repetition *
▪ Membership in
▪ Identity is

Computer Science Department, UET Lahore.


List Operator: Slicing
Slicing Operator is used to access a range of
elements in lists by using the operator [ : ] .
my_list = [55,65,75,85,95]
print(my_list[1:3])
Output:
[65,75]

Computer Science Department, UET Lahore.


List operator: Concatenation
We can “+” operator to combine two lists. The
process is called concatenation.

my_list=[1,2,3]
your_list=[4,5,6]
our_list=my_list+your_list
print(our_list) Output:
[1, 2, 3, 4, 5, 6]

Computer Science Department, UET Lahore.


List operator: Repetition
We use “*” operator to repeat a list for given
number of times.

our_list = [1,2,3,4,5,6]
print(our_list * 2)
Output:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6,]

Computer Science Department, UET Lahore.


List operator: Membership
The ‘in’ operator is used to check if a value exists in
a sequence or not.
Evaluates to true if it finds a variable in the
specified sequence and false otherwise.
list1 = [1,2,3]
list2 = [3,4,5]
Output:
for x in list1:
Not overlapping
if x in list2:
print(“Overlapping”) Not overlapping
else: Overlapping
print(“Not overlapping”)

Computer Science Department, UET Lahore.


List Method in Python
Method Description

append() Adds an item to the end of list

extend() Adds item(s) to the end of list

insert() Adds item to the specified index


remove() Deletes the given item from the list

reverse() Reverse the order of the list

sort() sorts the list

clear() Removes all the items from the list

copy() Returns a copy of the list

count() Returns the total number of time element occurred in list

index() Returns the index of the specified element in the list

Computer Science Department, UET Lahore.


Methods for Lists?
To add an item to end of list
my_list = [55,65,75,85,95] we use method append()
my_list.append(105) Output:
print(my_list) [55,65,75,85,95,105]

my_list = [55,65,75,85,95] To add multiple items to end


of list we use method extend()
my_list.extend([105,115,125])
Output:
print(my_list)
[55,65,75,85,95,105,115,125]

my_list = [55,65,75,85,95] To insert items at desired index


of list we use method insert()
my_list.insert(2,115) Output:
print(my_list) [55,65,115,75,85,95]
Computer Science Department, UET Lahore.
Methods for Lists?
To remove an item from list
my_list = [55,65,75,85,95] we use method remove()
my_list.remove(65) Output:
print(my_list) [55,75,85,95]

my_list = [55,65,75,85,95] To reverse the order of a list in


Python of list we use method
my_list.reverse() reverse()
print(my_list) Output:
[95,85,75,65,55]
my_list = [65,95,75,85,55] To sort list items in Python
we use method sort()
my_list.sort() Output:
print(my_list) [55,65,75,85,95]
Computer Science Department, UET Lahore.
Methods for Lists?
To sort a list in descending order
my_list = [65,95,75,85,55] we use method sort()
my_list.sort(reverse=True)Output:
print(my_list) [95,85,75,65,55]

my_list = [55,65,75,85,95] To copy a list in Python, we use


method copy()
your_list=my_list.copy()
print(your_list) Output:
[55,65,75,85,95]
my_list = [95,95,75,95,55] To count the numbers of times an item
appears in list, we use method count()
my_list.count(95) Output:
print(my_list) 3
Computer Science Department, UET Lahore.
Built-in Functions of List
Method Description

all() Adds True if all items are true (list, tuples, dictionaries)

any() Adds True if any item is true (list, tuples, dictionaries)

len() Returns the total length of the list/string


sum() Returns the sum of all elements in the list

list() Convert an iterable to a list (list, tuples, dictionaries)

min() Returns the minimum/smallest element of the list

max() Returns the maximum/largest element of the list

sorted() Returns a new sorted list

Computer Science Department, UET Lahore.


Tuples in Python

Computer Science Department, UET Lahore.


Learning Objectives
• Define why do we need Tuples in Python.

• Learn about the Mutable and immutable data structures

• Define and implement of Tuples

• Define, understand, and implement functions of Tuples

Computer Science Department, UET Lahore.


Why do we need tuple in Python?
A tuple is also used to store multiple data of
the same type or different type.

Computer Science Department, UET Lahore.


What is a tuple in Python?
A tuple is a collection of items which is:
1. Ordered
2. Unchangeable
3. allow duplicate values.

Computer Science Department, UET Lahore.


How tuple is different from list?
▪ Tuples are immutable objects while the lists are
mutable.
▪ This means that tuples cannot be changed while the
lists can be modified.
▪ Tuples use parentheses (), whereas lists use square
brackets [].

Computer Science Department, UET Lahore.


Creating a tuple in Python?
Tuple is creating by placing all the items
(elements) inside a round bracket (), separated
by commas(,).
Caution:
To create a tuple with only one item, you have
to add a comma after the item, otherwise
Python will not recognize it as a tuple.

Computer Science Department, UET Lahore.


Creating a tuple in Python?
To create a tuple with multiple item, you add
comma after every element except the last
one.
# Empty tuple
my_tuple = ()
# tuple of integers
my_tuple = (1,2,3)
# tuple of Mixed Data Types
my_tuple = (1, “Hello”, 3.5)

Computer Science Department, UET Lahore.


Accessing item from a tuple?
You can access tuple items by referring to the
index number, inside square brackets [] same
as we access element from a list.

my_tuple = (1,2,3,4,5)
print(my_tuple[1:3])
output:
2,3

Computer Science Department, UET Lahore.


How to update a tuple?
Tuple is unchangeable but you can convert tuple
into list, change a list, and then convert list
back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y) output:
print(x) ("apple", “kiwi", "cherry")

Computer Science Department, UET Lahore.


How to add an item in a tuple?
Since tuples are immutable, they do not have a build-
in append() method, but you can convert it into a list,
add your item(s), and convert it back into a tuple.
To add an item to end of tuple
my_tuple = (55,65,75,85,95) We can use this technique
your_list = list(my_tuple)
your_list.append(105)
my_tuple = tuple(your_list)
Output:
print(my_tuple) (55,65,75,85,95,105)

Computer Science Department, UET Lahore.


How to add an item in a tuple?
In Python, You are allowed to add tuples to tuples, so if
you want to add one item, (or many), create a new tuple
with the item(s), and add it to the existing tuple.
To add multiple item to end of tuple
my_tuple = (55,65,75,85,95) We can use this technique
your_tuple = (105,115,125)
my_tuple = my_tuple + your_tuple
print(my_tuple) Output:
(55,65,75,85,95,105,115,125)

Computer Science Department, UET Lahore.


How to remove an item in a tuple?
In the same way you add an element in a tuple, you can
remove an element from a tuple.

To remove an item from a tuple


my_tuple = (55,65,75,85,95) We can use this technique
your_list = list(my_tuple)
your_list.remove(75)
my_tuple = tuple(your_list)
Output:
print(my_tuple) (55,65,85,95)

Computer Science Department, UET Lahore.


How to unpack a tuple?
When we create a tuple, we normally assign values to it.
This is called "packing" a tuple. But, in Python, we are
also allowed to extract the values back into variables.
This is called "unpacking":
Example Unpacking:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green) Output: Apple
print(yellow) Output: banana
Output: cherry
print(red)

Computer Science Department, UET Lahore.


How to unpack a tuple?
Using Asterisk (*): If the number of variables is less
than the number of values, you can add an * to the
variable name and the values will be assigned to the
variable as a list
Example Unpacking:
fruits = ("apple", "banana", "cherry“, “strawberry”)
(green, yellow, red) = fruits
print(green) Output: Apple
print(yellow) Output: banana
Output: [cherry, strawberry]
print(red)

Computer Science Department, UET Lahore.


How to unpack a tuple?
Using Asterisk (*): If the number of variables is less
than the number of values, you can add an * to the
variable name and the values will be assigned to the
variable as a list
Example Unpacking:
fruits = ("apple", "banana", "cherry“, “strawberry”)
(green, yellow, red) = fruits
print(green) Output: Apple
print(yellow) Output: banana
Output: [cherry, strawberry]
print(red)

Computer Science Department, UET Lahore.


Basic tuple 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.
Expression Results Description

Len((1,2,3)) 3 Length

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

(‘Hi’,) * 4 (‘Hi’,’Hi’,’Hi’,’Hi’) Repetition


3 in (1,2,3) True Membership

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


print(x)

Computer Science Department, UET Lahore.


Built-in Functions of Tuple
Method Description

Returns the number of times a specified value occurs


count() in a tuple

Searches the tuple for a specified value and returns


index() the position of where it was found

len() Returns the total length of the tuple

tuple(list) Convert list into tuple.

cmp(tuple1,tuple2) Compares elements of both tuples.

Computer Science Department, UET Lahore.


Learning Objective
In this lecture, we learnt what is a list
and tuple, why we need list and tuples,
how to create and update a list and
tuples in Python and which operations
we can perform on list and tuples.

Computer Science Department, UET Lahore.


Conclusion
● To store multiple data in programming, list
and tuple is used.
● With the help of various methods and
operators, we can perform many
operations on list and tuple.
● Built-In functins can also be used on
lists and tuple.

Computer Science Department, UET Lahore.


Self Assessment
Solve the Following Programs

1. Write a program to sum all the elements in a list.


2. Write a program to get a largest element in a list.
3. Write a program to check a list is empty or not?
4. Write a program to copy a lsit.

Computer Science Department, UET Lahore.


Self Assessment
Solve Following Programs

1. Write a Program that takes two lists and returns


true if they have at least one common element.
2. Write a program to generate and print a list of first
and last 5 elements where the values are square of
numbers between 1 and 30 (both included).

Computer Science Department, UET Lahore.


Self Assessment
Solve Following Programs

1. Write a program to print the numbers of a specified


list after removing even numbers from it.
2. Write a program to print a specified list after
remvoing the 0th, 4th and 5th elements.

Sample list=[‘yellow”,”Pink”,”Red”,”Green”,”Blue”,”Purple”]

Output =[‘”Pink”,”Red”,”Green”]

Computer Science Department, UET Lahore.


Self Assessment
Solve the Following Programs

1. Write a program to print the first element of a


tuple.
2. Write a program to get a last element in a tuple
using negative indexing.
3. Write a program to use a range of indexes to print
the third, fourth, and fifth item in the tuple

Computer Science Department, UET Lahore.


Self Assessment
Solve Following Programs

1. Write a program to print the numbers of a specified


tuple after removing even numbers from it.
2. Write a program to print a specified tuple after
remvoing the 0th, 4th and 5th elements.

Sample list=(”yellow”,”Pink”,”Red”,”Green”,”Blue”,”Purple”)

Output =(”Pink”,”Red”,”Green”)

Computer Science Department, UET Lahore.

You might also like