Python Course - VII Lists and Tuples
Python Course - VII Lists and Tuples
Hand Notes 7
1
Python Programming - IV
LIST
A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. This
is easy to imagine if you can think of a shopping list where you have a list of items to buy, except that you probably
have each item on a separate line in your shopping list whereas in Python you put commas in between them. The list
of items should be enclosed in square brackets so that Python understands that you are specifying a list. Once you
have created a list, you can add, remove or search for items in the list. Since we can add and remove items, we say
that a list is a mutable data type i.e. this type can be altered.
Properties of List
INBUILT FUCTIONS
Method Description Example
append() Adds an element at the end of the list thislist.append("orange")
clear() Removes all the elements from the list thislist.clear()
copy() Returns a copy of the list x = fruits.copy()
count() Returns the number of elements with the specified value x = fruits.count("cherry")
extend() Add the elements of a list (or any iterable), to the end of the fruits.extend(cars)
current list
index() Returns the index of the first element with the specified value x = fruits.index("cherry")
insert() Adds an element at the specified position fruits.insert(1, "orange")
pop() Removes the element at the specified position fruits.pop(1)
remove() Removes the item with the specified value fruits.remove("banana")
reverse() Reverses the order of the list fruits.reverse()
sort() Sorts the list fruits.sort()
2
Python Programming - I
TUPLE
Tuples are used to hold together multiple objects. Think of them as similar to lists, but without the extensive
functionality that the list class gives you. One major feature of tuples is that they are immutable like strings i.e. you
cannot modify tuples. Tuples are defined by specifying items separated by commas within an optional pair of
parentheses. Tuples are usually used in cases where a statement or a user-defined function can safely assume that
the collection of values i.e. the tuple of values used will not change.
sum=0
for x in var1:
sum+= x
print("Sum of the values are ",sum)
#marksList = [0]*5
marksList = ['0',0,0.0,False,0]
sum=0
print("Length of the list is ",len(marksList))
for i in range(0,5):
marksList[i] = int(input("Enter the marks in Subject "+str(i+1)+" : "))
sum+=marksList[i]
print("You have entered following marks: ",marksList, "and total marks is ",sum)
marksList2=[]
sum=0
print("Length of the list is ",len(marksList))
for i in range(0,5):
var1 = int(input("Enter the marks in Subject "+str(i+1)+" : "))
marksList2.append(var1)
sum+=marksList2[i]
#sum+=var1
print("You have entered following marks: ",marksList2, "and total marks is ",sum)
print("Now the length is ",len(marksList2))
3
Python Programming - I
fruits1.insert(0,"Mango")
fruits1.insert(2,"Banana")
print("Fruits list has ",fruits1)
fruits1.pop(1)
print("Fruits list after POP(1) ",fruits1)
fruits1.remove("Banana")
print("Fruits list after Remove(Banana) ",fruits1)
fruits1.insert(1,"Orange")
fruits1.insert(2,"Banana")
fruits1.insert(3,"Cherry")
fruits1.insert(4,"Apple")
fruit2check = "Pineapple"
print(fruit2check in fruits1)
fruits1.sort()
print("Sorted order is ", fruits1)
###Tuple
var1=(1,2,3)
print("Values in Tuple ",var1)
print("Second Value in Tuple ",var1[1])
#var1[1] = 5 #Immutable
fruits1 = []
fruits1.insert(1,"Orange")
fruits1.insert(0,"Mango")
fruits1.insert(2,"Banana")
print("Type of Fruits ",type(fruits1))
fruits1 = tuple(fruits1)
print("Type of Fruits ",type(fruits1))
fruits1 = list(fruits1)
print("Type of Fruits ",type(fruits1))
#Tuples are very similar to List but doesnt allow mutability because of which
# it is faster to do programs using Tuples
More on Tuples
A tuple is just like a list of a sequence of immutable python objects.
The difference between list and tuple is that list are declared in square brackets and can be changed while tuple is
declared in parentheses and cannot be changed.
However, you can take portions of existing tuples to make new tuples.
Syntax
Tup = ('Jan','feb','march')
#Comparing Tuples
#A comparison operator in Python can work with tuples.
#The comparison starts with a first element of each tuple.
#If they do not compare to =,< or > then it proceed to the second element and so on.
#It starts with comparing the first element from each of the tuples.
4
Python Programming - I
#case 1
a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
#case 2
a=(5,6)
b=(5,4)
if (a>b):print("a is bigger")
else: print ("b is bigger")
#case 3
a=(5,6)
b=(6,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
#Inside the brackets, the expression is a tuple. We could use tuple assignment in a for
loop to navigate this dictionary.
for last, first in directory:
print(first, last, directory[last, first])
#This loop navigates the keys in the directory, which are tuples. It assigns the
elements of each tuple to last and first and then prints the name and corresponding
telephone number.
#Deleting Tuples
#Tuples are immutable and cannot be deleted, but
# deleting tuple entirely is possible by using the keyword "del."
del a
#Slicing of Tuple
5
Python Programming - I
#To fetch specific sets of sub-elements from tuple or list, we use this unique function
called slicing. Slicing is not only applicable to tuple but also for array and list.
x = ("a", "b","c", "d", "e")
print(x [2:4])
LAMBDA
lambda operator or lambda function is used for creating small, one-time and anonymous function objects in Python.
Basic Syntax: lambda arguments : expression
lambda operator can have any number of arguments, but it can have only one expression. It cannot contain any
statements and it returns a function object which can be assigned to any variable.
LAMBDA Programs in the Class
LIST FUNCTIONS
These are three functions which facilitate a functional approach to programming. We will discuss them one by one
and understand their use cases:
Map
Filter
Reduce
6
Python Programming - I
Map
We spend lot of time analyzing list of data like: List of stock prices, Orders, Customer profiles
Map applies a function to all the items in an input_list
map() function returns a map object(which is an iterator) of the results after applying the given
function to each item of a given iterable (list, tuple etc.)
Problem Blueprint:
Data: a1, a2, … ,an
Function: f
map(f, data) returns Iterator over: f(a1), f(a2), …, f(an)
Blueprint
map(function_to_apply, list_of_inputs)
Most of the times we want to pass all the list elements to a function one-by-one and then collect the output.
#Map allows us to implement this in a much simpler and nicer way. Here you go
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
def multiply(x):
return (x * x)
def add(x):
return (x + x)
FILTER
As the name suggests, filter creates a list of elements for which a function returns true. It filters out the data you do
not need. E.g. Find all data above average
The filter resembles a for loop but it is a builtin function and faster.
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
7
Python Programming - I
print(less_than_zero)
import statistics
data_list = [5, 1, 8,2,5,9,12,15,18]
avg_val = statistics.mean (data_list)
above_avg = list(filter(lambda x: x > avg_val, data_list))
print(above_avg)
Reduce
Reduce is a really useful function for performing some computation on a list and returning the
result.
It applies a rolling computation to sequential pairs of values in a list.
For example, if you wanted to compute the product of a list of integers.
Normal way you might go about doing this task in python is using a basic for loop
In Python 3, it is no longer a built-in function, we need to call from functools.reduce()
How it works
# Without Reduce
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
print("Without Reduce concept, output: ", product)
# product = 24
#Now let’s try it with reduce: same logic
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print("Now with Reduce, output: ", product)
8
Python Programming - I
Assignments
1. Write a Python program to sum all the items in a list.
2. Write a Python program to multiplies all the items in a list.
3. Write a Python program to get the largest number from a list.
4. Write a Python program to get the smallest number from a list.
5. Write a Python program to count the number of strings where the string length is 2 or more and the
first and last character are same from a given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221’]
Expected Result : 2
6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from
a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
13. Write a Python program to generate a 3*4*6 3D array whose each element is *.
14. Write a Python program to print the numbers of a specified list after removing even numbers from
it.
15. Write a Python program to shuffle and print a specified list.
16. Write a Python 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).
17. Write a Python program to generate and print a list except for the first 5 elements, where the values
are square of numbers between 1 and 30 (both included).
18. Write a Python program to generate all permutations of a list in Python.
19. Write a Python program to get the difference between the two lists.
20. Write a Python program access the index of a list.
- - - End of Session 4 - - -