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

Python Unit 5

The document discusses Python tuples. Some key points: - Tuples are ordered, immutable sequences of elements that can contain duplicate values. They are indexed and allow slicing. - Tuples are created using parentheses, e.g. tup1 = (1,2,3). An empty tuple is tup2 = (). - Elements can be accessed via indexing like lists, e.g. tup1[0]. Slicing also works similarly. - Common operators like + and * can be used to concatenate and repeat tuples. Membership is checked with 'in'.

Uploaded by

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

Python Unit 5

The document discusses Python tuples. Some key points: - Tuples are ordered, immutable sequences of elements that can contain duplicate values. They are indexed and allow slicing. - Tuples are created using parentheses, e.g. tup1 = (1,2,3). An empty tuple is tup2 = (). - Elements can be accessed via indexing like lists, e.g. tup1[0]. Slicing also works similarly. - Common operators like + and * can be used to concatenate and repeat tuples. Membership is checked with 'in'.

Uploaded by

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

G H Raisoni Institute of

Business Management, Jalgaon


Department of Computer Application

Department of Computer Application


Academic Year: 2022-23
FourSemester

Course Code: BCA-CEC-2A

Course Name: Python Programming

Prepared By: Mrs. Sarita Charkha


Unit 4:Tuple and Database

Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple
is similar to lists since the value of the items stored in the list can be changed,
whereas the tuple is immutable, and the value of the items stored in the tuple
cannot be changed.
Characteristics
 Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.

 Ordered
When we say that tuples are ordered, it means that the items have a defined order,
and that order will not change.

 Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.

 Allow Duplicates
Since tuples are indexed, they can have items with the same value:

Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed
with the small
() brackets. The parentheses are optional but it is good practice to use. A tuple can
be defined
as follows.
1. T1 = (101, "Peter", 22)
2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4. print(type(T1))
5. print(type(T2))
6. print(type(T3))

Note: The tuple which is created without using parentheses is also known as
tuple packing.

Prof.Sarita Charkha Page 2


Unit 4:Tuple and Database

An empty tuple can be created as follows.


T4 = ()
Creating a tuple with single element is slightly different. We will need to put
comma after the element to declare the tuple.

tup1 = ("JavaTpoint")
print(type(tup1))
#Creating a tuple with single element
tup2 = ("JavaTpoint",)
print(type(tup2))

Output:

<class ‘str’>

<class ‘tuple’>

A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed by using their specific index value.
Consider the following example of tuple:

Example - 1
tuple1 = (10, 20, 30, 40, 50, 60)

print(tuple1)

count = 0

for i in tuple1:

print("tuple1[%d] = %d"%(count, i))

count = count+1

output:

(10, 20, 30, 40, 50, 60)


tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30

Prof.Sarita Charkha Page 3


Unit 4:Tuple and Database

tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
Ex2:
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i))
count = count+1
output:
Enter the tuple elements ...123456
('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists. The indexing in the tuple
starts from 0 and goes to length(tuple) - 1. The items in the tuple can be accessed
by using the index [] operator. Python also allows us to use the colon operator to
access multiple items in the tuple.

Prof.Sarita Charkha Page 4


Unit 4:Tuple and Database

Consider the following image to understand the indexing and slicing in


detail.

Consider the following example:


tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])
Output:
• 1
• 2
• 3
• tuple index out of range

Range of Indexes

Prof.Sarita Charkha Page 5


Unit 4:Tuple and Database

You can specify a range of indexes by specifying where to start and where to end
the range.

When specifying a range, the return value will be a new tuple with the specified
items.

Example:
# Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[2:5])

Output:
Note: The search will start at index 2 (included) and end at index 5 (not included).
Example:

This example returns the items from the beginning to, but NOT included, "kiwi":

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[:4])

Negative Indexing
The tuple element can also access by using negative indexing. The index of -1
denotes the rightmost element and -2 to the second last item and so on. The
elements from left to right are traversed using the negative indexing. Consider
the following
example:

tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
print(tuple1[:-1])
print(tuple1[-2:])

Prof.Sarita Charkha Page 6


Unit 4:Tuple and Database

Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
Deleting Tuple

Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples
are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.

tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0] #error, as we cant delete items form tuple

print(tuple1)

del tuple1 # it will delete whole tuple


print(tuple1)# Error tuple is not defined

Example:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[:4])
print(thistuple[2:])

print(thistuple[-4:-1])

output:

• ('apple', 'banana', 'cherry', 'orange')

Prof.Sarita Charkha Page 7


Unit 4:Tuple and Database

• ('cherry', 'orange', 'kiwi', 'melon', 'mango')

• ('orange', 'kiwi', 'melon')

Example: Check Item in list

thistuple = ("apple", "banana", "cherry")


if ("apple" in thistuple):
print("Yes, 'apple' is in the fruits tuple")

output:

Yes, ‘apple’ is in the fruits tuple

Example:

thistuple = ("apple", "banana", "cherry")

if ("kiwi" in thistuple):

print("Yes, 'apple' is in the fruits tuple")

else:

print(" Not match")

Output:

Not match

Example: Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Prof.Sarita Charkha Page 8


Unit 4:Tuple and Database

Output:

("apple", "kiwi", "cherry")

Example : Tuples are unchangeable, so you cannot remove items from it, but you
can use the same workaround as we used for changing and adding tuple items:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Example: The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Example: Unpacking a Tuple

When we create a tuple, we normally assign values to it. This is called "packing" a
tuple: Packing a tuple:

fruits = ("apple", "banana", "cherry")

But, in Python, we are also allowed to extract the values back into variables. This
is called "unpacking":

fruits = ("apple", "banana", "cherry")


(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

output:
apple

Prof.Sarita Charkha Page 9


Unit 4:Tuple and Database

banana
cherry

Basic Tuple operations

The operators like concatenation (+), repetition (*), Membership (in) works in the
same way asthey work with the list. Consider the following table for more detail.
 (+)Operator: The + operator returns a tuple containing all the elements of
the first and the second tuple object.
Ex.
t1=(1,2,3)
t2=(4,5,6)
print(t1+t2)
Output: (1,2,3,4,5,6)
Ex.
t1=(1,2,3)
t2=(4,5,6)
t=('a','b','c')
print(t1+t2+t)
output: (1,2,3,4,5,6,’a’,’b’,’c’)

Ex.

t1=(1,2,3)
t2=(4,5,6)
t2=t2+(7,)
print(t2)
output: (4,5,6,7)

Ex:

print ((1, 2, 5, 8) + (2, 9, 4));


output(1,2,3,5,8,2,9,4)
 The (* )operator Concatenates multiple copies of the same tuple.

Prof.Sarita Charkha Page 10


Unit 4:Tuple and Database

Ex:

t1=(1,2,3)
print(t1*4)
output: (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

 The [ ] operator Returns the item at the given index. A negative index counts
the position from the right side.

 The [:] operator returns the items in the range specified by two index
operands separated by the : symbol.
If the first operand is omitted, the range starts from zero. If the second
operand is omitted, the range goes up to the end of the tuple

 The in operator returns true if an item exists in the given tuple.

Example:
t1=(1,2,3,4,5,6)
print(5 in t1) output: true
print(10 in t1) Output:false
 The not in operator returns true if an item does not exist in the given tuple.
t1=(1,2,3,4,5,6)
print( 4 not in t1)
False
print( 10 not in t1)
True

Python Tuple inbuilt functions


Prof.Sarita Charkha Page 11
Unit 4:Tuple and Database

1. len() function
As you might have already guessed, this function is used to get the number of
elements inside any tuple.

>>> t = 1, 2, 3

>>> print (len(t))

Output: 3

2. cmp() function
This is used to compare two tuples. It will return either 1, 0 or -1, depending upon
whether the two tuples being compared are similar or not.

The cmp() function takes two tuples as arguments, where both of them are
compared. If T1 is the first tuple and T2 is the second tuple, then:

 if T1 > T2, then cmp(T1, T2) returns 1

 if T1 = T2, then cmp(T1, T2) returns 0

 if T1 > T2, then cmp(T1, T2) returns -1

3. max() and min() function


To find the maximum value in a tuple, we can use the max() function, while for
finding the minimum value, min() function can be used.

t = (1, 4, 2, 7, 3, 9)

print (max(t))

print (min(t))
output:
9
1

Prof.Sarita Charkha Page 12


Unit 4:Tuple and Database

4. The sorted() and sum() Function

This method takes a tuple as an input and returns a sorted list as an output. Moreover,
it does not make any changes to the original tuple.

tup = (22, 3, 45, 4, 2, 56, 890, 1)

print(sum(tup))

print(sorted(tup))

output:1023

(1,2,3,4,22,45,56,890)

Where to use tuple?


Using tuple instead of list is used in the following scenario.
1. Using tuple instead of list gives us a clear idea that tuple data is constant and
must not be
changed.
2. Tuple can simulate a dictionary without keys. Consider the following nested
structure, which can be used as a dictionary.
[(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]

Note:

 List is a collection which is ordered and changeable. Allows duplicate


members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
 Dictionary is a collection which is ordered** and changeable. No duplicate
members.

Prof.Sarita Charkha Page 13


Unit 4:Tuple and Database

Python can be used in database applications. One of the most popular databases is
MySQL
MySQL Database
To be able to experiment with the code examples in this tutorial, you should have
MySQL installed on your computer.

You can download a MySQL database at https://www.mysql.com/downloads/.

Install MySQL Driver


Python needs a MySQL driver to access the MySQL database.

In this tutorial we will use the driver "MySQL Connector".

We recommend that you use PIP to install "MySQL Connector".

PIP is most likely already installed in your Python environment.

Test MySQL Connector

To test if the installation was successful, or if you already have "MySQL


Connector" installed, create a Python page with the following content:

demo_mysql_test.py:

import mysql.connector

#if this page is executed with no errors, you have the "mysql.connector"
module installed.

Create Connection

Start by creating a connection to the database.

Use the username and password from your MySQL database:

demo_mysql_connection.py:

Prof.Sarita Charkha Page 14


Unit 4:Tuple and Database

import mysql.connector

mydb = mysql.connector.connect
(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)

Creating a Table

To create a table in MySQL, use the "CREATE TABLE" statement.

Make sure you define the name of the database when you create the connection

Create a table named "customers":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address


VARCHAR(255))")

Insert Into Table

To fill a table in MySQL, use the "INSERT INTO" statement.

Prof.Sarita Charkha Page 15


Unit 4:Tuple and Database

Example

Insert a record in the "customers" table:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Update Table
You can update existing records in a table by using the "UPDATE" statement:

Overwrite the address column from "Valley 345" to "Canyon 123":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

Prof.Sarita Charkha Page 16


Unit 4:Tuple and Database

mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley
345'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

Join Two or More Tables


You can combine rows from two or more tables, based on a related column
between them, by using a JOIN statement.

Consider you have a "users" table and a "products" table:

USER:

{ id: 1, name: 'John', fav: 154},


{ id: 2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}
PRODUCTS:
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }

These two tables can be combined by using users' fav field and products' id field.

Example

Join users and products to see the name of the users favorite product:

Prof.Sarita Charkha Page 17


Unit 4:Tuple and Database

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
print(x)

OUTPUT:
• ('John', 'Chocolate Heaven')
('Peter', 'Chocolate Heaven')
('Amy', 'Tasty Lemon')

Prof.Sarita Charkha Page 18

You might also like