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

Python 4

The document discusses Python lists and tuples. It describes what they are, their characteristics, how to define, index, slice, update and perform common operations on lists and tuples. It also provides examples of various methods that can be used on lists and tuples.

Uploaded by

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

Python 4

The document discusses Python lists and tuples. It describes what they are, their characteristics, how to define, index, slice, update and perform common operations on lists and tuples. It also provides examples of various methods that can be used on lists and tuples.

Uploaded by

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

Python Programming

List
 A list in Python is used to store the sequence of various types of data.
 Python lists are mutable types which means we can modify its
element after it is created.
 However, Python consists of many data types that are capable to store
the sequences, but the most common and reliable type is the list.
 A list can be defined as a collection of values or items of different
types. The items in the list are separated with the comma (,) and
enclosed with the square brackets [].
 A list can be define as below
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
 If we try to print the type of L1, and L2 using type() function then it
will come out to be a list.
print(type(L1))
print(type(L2))
 Output:
 <class 'list'> <class 'list'>
Characteristics of Lists

The list has the following characteristics:


The lists are ordered.
The element of the list can access by index.
The lists are the mutable type.
A list can store the number of various elements.
emp=["John",102,"USA"]
Dep1=["CS",10]
Dep2=["IT",11]
HOD_CS=[10,"Mr. Holding"]
HOD_IT=[11,"Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%
(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\
nName: %s, ID: %s"%(Dep1[0],Dep1[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%
(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
List indexing and splitting
 The indexing is processed in the same way as it happens with the strings. The
elements of the list can be accessed by using the slice operator [].
 The index starts from 0 and goes to (length – 1). The first element of the list is
stored at the 0th index, the second element of the list is stored at the 1st index,
and so on.
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
 The start denotes the starting index position of the list.
 The stop denotes the last index position of the list.
 The step is used to skip the nth element within a start:stop
 Consider the following example:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for
(index -1).
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
 Python provides the flexibility to use the negative indexing also.
 The negative indices are counted from the right.
 The last element (rightmost) of the list has the index -1; its adjacent left
element is present at the index -2 and so on until the left-most elements
are encountered.
Let's have a look at the following example where we will
use negative indexing to access the elements of the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])

Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Updating List values
 Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.
 Python also provides append() and insert() methods, which can be
used to add values to the list.
 Consider the following example to update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element Output:
[1, 2, 3, 4, 5, 6]
list[1:3] = [89, 78]
[1, 2, 10, 4, 5, 6]
print(list) [1, 89, 78, 4, 5, 6]
# It will add value at the end of the list [1, 89, 78, 4, 5, 25]
list[-1] = 25
print(list)
Python List Operations
 The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings.
 Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]

Operator Description Example

Repetition The repetition operator enables the l1*2 => [1, 2, 3, 4, 1, 2,


list elements to be repeated multiple 3, 4]
times.
Concatenation It concatenates the list mentioned on l1+l2 => [1, 2, 3, 4, 5, 6,
either side of the operator. 7, 8]

Membership It returns true if a particular item print(2 in l1)


exists in a particular list otherwise Output: True.
false.
Iteration The for loop is used to iterate over for i in l1:
the list elements. print(i)
Output: 1 2 3 4
Length It is used to get the length of the list len(l1) = 4
Iterating a List
 A list can be iterated by using a for - in loop. A simple list containing
four strings, which can be iterated as follows.
list = ["John", "David", "James", "Jonathan"]
# The i variable will iterate over the elements of the List and contains eac
h element in each iteration.
for i in list:
print(i)

Output:
John
David
James
Jonathan
Adding elements to the list
Python provides append() function which is used to add an element to the list.
However, the append() function can only add value to the end of the list.
Example:
l =[]
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:3
Enter the item:25
Enter the item:46
Enter the item:12
printing the list items.. 25 46 12
Removing elements from the list
Python provides the remove(element) function which is used to
remove the element from the list.
Example -
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:
printing original list: 0 1 2 3 4
printing the list after the removal of first element... 0 1 3 4
Python built-in methods
insert(): Inserts an elements at specified position.
Syntax: list.insert(position, element)
Note: Position mentioned should be within the range
of List, as in this case between 0 and 4, elsewise
would throw IndexError.
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2,10087)
print(List)
Output:
['Mathematics', 'chemistry', 10087, 1997, 2000]
extend(): Adds contents of List2 to the end of List1.
Syntax:List1.extend(List2)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1) # [1, 2, 3, 2, 3, 4, 5]
# Add List1 to List2 now
List2.extend(List1)
print(List2)
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
sum() : Calculates sum of all the elements of List.
Syntax: sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15

count() : Calculates total occurrence of given element of List.


Syntax: List.count(element)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output:
4
More List methods
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
insert(index,value) Adds an element at the specified position
pop() Removes the element at the specified position
reverse() Reverses the order of the list
sort() Sorts the list
max() Returns the maximum value of the list
min() Returns the minimum value of the list
Example: to remove duplicates from list
list=[3,4,4,6,2,3,6,5,2,1,7]
U_list=[]
for i in list:
if i not in U_list:
U_list.append(i)
print(U_list) # [3, 4, 6, 2, 5, 1, 7]

Example: find the second largest element of the list


a= [3, 6, 9, 3, 6, 3, 6, 8, 3, 9, 8, 6, 6]
u=[]
if(len(a)<2):
print("invalid list")
else:
for i in a:
if i not in u:
u.append(i)
u.sort(reverse= True);
Example: find the common element in two lists.
list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
for i in list1:
if i in list2:
print(i, end = “ ”) # 1 7

Example: find the element of the list which are not


present in another list.
list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
for i in list1:
if i not in list2:
print(i, end = " ") #359
Tuple
A tuple is a collection which is ordered and
unchangeable.
In Python, tuples are written with round brackets. Tuples
are a sequence of comma-separated values enclosed in
parentheses.
There are various ways in which we can access the
elements of a tuple.
1. Indexing
2. Negative Indexing
3. Slicing
Indexing
We can use the index operator [] to access an item in a
tuple, where the index starts from 0.
So, a tuple having 6 elements will have indices from 0
to 5. Trying to access an index outside of the tuple
index range(6,7,... in this example) will raise
an IndexError.
The index must be an integer, so we cannot use float or
other types. This will result in TypeError.
Example
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# IndexError: list index out of range


# print(my_tuple[6])

# Index must be an integer


# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
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.
Example
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])
Slicing
We can access a range of items in a tuple by using the
slicing operator colon : .
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 the index that will slice
the portion from the tuple.

Elemens P R O G A M
Positive Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1
Example
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m')
# elements 2nd to 4th
print(my_tuple[1:4]) # Output: ('r', 'o', 'g')

# elements beginning to 2nd


print(my_tuple[:-5]) # Output: ('p', 'r')

# elements 5th to end


print(my_tuple[5:]) # Output: ('a', 'm')

# elements beginning to end


Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be
changed once they have been assigned. But, if the
element is itself a mutable data type like a list, its
nested items can be changed.
We can also assign a tuple to different values
(reassignment).
Example
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])

my_tuple[1] = 9
# TypeError: 'tuple' object does not support item assignment

# However, item of mutable element can be changed


my_tuple[3][0] = 9
print(my_tuple) # Output: (4, 2, 3, [9, 5])

# Tuples can be reassigned


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm')

print(my_tuple)
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm')
Packing of Tuples
When we create a tuple, we normally assign values to it.
This is called "packing" a tuple:
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")
Unpack Tuples
In Python, we are also allowed to extract the values back into variables.
This is called "unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
OUTPUT:
apple
Banana
cherry
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
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
OUTPUT:
apple
Banana
['cherry', 'strawberry', 'raspberry‘]
Tuple Operations
Length
Use the len() function to determine the length of the
tuple, then start at 0 and loop your way through the
tuple items by refering to their indexes.
Remember to increase the index by 1 after each
iteration.
Example
Print all items, using a while loop to go through all the
index numbers:
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
OUTPUT:
apple
banana
cherry
Concatenation
Concatenation of Two Tuples
To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
OUTPUT:
('a', 'b', 'c', 1, 2, 3)
Repetition
If you want to repeate (multiply) the content of a tuple
a given number of times, you can use the * operator:
Example:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
OUTPUT:
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Membership
Membership operators are operators used to validate
the membership of a value. It test for membership in a
sequence, such as strings, lists, or tuples.
in operator : 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.
not in’ operator- Evaluates to true if it does not finds
a variable in the specified sequence and false
otherwise.
Difference Between List and Tuple
List and Tuple in Python are the classes of Python
Data Structures.
The list is dynamic, whereas the tuple has static
characteristics. This means that lists can be modified
whereas tuples cannot be modified, the tuple is faster
than the list because of static in nature.
Lists are denoted by the square brackets but tuples are
denoted as parenthesis.
List
The list has the following features -
You can use Python lists to store data of multiple types
simultaneously.
Lists help preserve data sequences and further process
those sequences in other ways.
Lists are dynamic.
Lists are mutable.
Lists are ordered.
An index is used to traverse a list.
Tuple

A python tuple has the following features -


Tuples are used to store heterogeneous and
homogeneous data.
Tuples are immutable in nature.
Tuples are ordered
An index is used to traverse a tuple.
Tuples are similar to lists. It also preserves the data
sequence.
As tuples are immutable, they are faster than the list
because they are static.
Memory Size
 import sys
a_list1 = []
a_tuple1 = ()
a_list2 = ["Geeks", "For", "Geeks"]
a_tuple2 = ("Geeks", "For", "Geeks")
print(“List1=", sys.getsizeof(a_list1))
print("Tuple1=", sys.getsizeof(a_tuple1))
print("List2=",sys.getsizeof(a_list2))
print("Tuple2=",sys.getsizeof(a_tuple2))
 OUTPUT:
List1= 56
Tuple1= 40
List2= 120
Tuple2= 64
Python Dictionary
Python Dictionary
Python Dictionary is used to store the data in a key-value
pair format. The dictionary is the data type in Python,
which can simulate the real-life data arrangement where
some specific value exists for some particular key.
It is the mutable data-structure.
The dictionary is defined into element Keys and values.
 Keys must be a single element
 Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the
collection of key-value pairs where the value can be any
Python object.
In contrast, the keys are the immutable Python object,
i.e., Numbers, string, or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs
enclosed with the curly brackets {}, and each key is separated
from its value by the colon (:).
The syntax to define the dictionary is given below.
Dict = {"Name": "Tom", "Age": 22}
In the above dictionary Dict, The keys Name and Age are the string
that is an immutable object.
Let's see an example to create a dictionary and print its content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"
GOOGLE"}
print(type(Employee)) # <class 'dict'>
print("printing Employee data .... ")
print(Employee) #{'salary': 25000, 'Age': 29, 'Company': 'GOOGLE',
'Name': 'John'}
Python provides the built-in function dict() method
which is also used to create dictionary. The empty
curly braces {} is used to create empty dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict) # {}

# Creating a Dictionary
# with dict() method
Dict = dict({1: ‘python', 2: ‘high', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict) # {1: ‘python', 2: ‘high', 3:'Point'}
Accessing the dictionary values
We have discussed how the data can be accessed in the
list and string by using the indexing.
However, the values can be accessed in the dictionary by
using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following
way.
Employee = {"Name": "John", "Age": 29}
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
Output:
printing Employee data ....
Name : John
Adding dictionary values
 The dictionary is a mutable data type, and its values can be updated by
using the specific keys.
 The value can be updated along with key Dict[key] = value.
 Note: If the key-value already present in the dictionary, the value
gets updated. Otherwise, the new keys added in the dictionary.
 Let's see an example to update the dictionary values.
# Creating an empty Dictionary
D = {}
# Adding elements to dictionary one at a time
D[0] = 'Peter'
D[7] = 'Joseph'
D[90] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(D)
Output:
Dictionary after adding 3 elements:
Deleting elements using del keyword
The items of the dictionary can be deleted by using
the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company"
:"GOOGLE"}
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "<string>", line 11, in <module>
NameError: name 'Employee' is not defined
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Com
pany":"GOOGLE"}
for x in Employee:
print(x)

Output:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee:
print(Employee[x])
Output:
John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by
using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee.values():
print(x)
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by
using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee.items():
print(x)
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
S. No Function Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.has_key(key) It returns true if the dictionary contains the
specified key.
3 dict.items() It returns all the key-value pairs as a tuple.
4 dict.keys() It returns all the keys of the dictionary.
5 dict.update(dict2) It updates the dictionary by adding the key-value
pair of dict2 to this dictionary.
6 dict.values() It returns all the values of the dictionary.
7 len() It returns length of the dictionary.
8 popItem() method removes the item that was last inserted
into the dictionary
9 pop() method removes the item usinh key from the
dictionary
Set
A set is a collection of the unordered items.
Each element in the set must be unique, immutable, and
the sets remove the duplicate elements.
Sets are mutable which means we can modify them after
their creation.
The set can be created by enclosing the comma-separated
immutable items with the curly braces {}.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday
", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
add() method
Months = set(["January","February", "March", "April", "May"
, "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
update() function
Months = set(["January","February", "March", "April", "Ma
y", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);

print("\nprinting the modified set ... ")


print(Months);

You might also like