Python Unit 5
Python Unit 5
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.
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:
count = count+1
output:
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
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.
Range of Indexes
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":
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:])
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)
Example:
print(thistuple[-4:-1])
output:
output:
Example:
if ("kiwi" in thistuple):
else:
Output:
Not match
Output:
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:
When we create a tuple, we normally assign values to it. This is called "packing" a
tuple: Packing a tuple:
But, in Python, we are also allowed to extract the values back into variables. This
is called "unpacking":
output:
apple
banana
cherry
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:
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
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
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
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:
t = (1, 4, 2, 7, 3, 9)
print (max(t))
print (min(t))
output:
9
1
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.
print(sum(tup))
print(sorted(tup))
output:1023
(1,2,3,4,22,45,56,890)
Note:
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.
demo_mysql_test.py:
import mysql.connector
#if this page is executed with no errors, you have the "mysql.connector"
module installed.
Create Connection
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect
(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
Creating a Table
Make sure you define the name of the database when you create the connection
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
Update Table
You can update existing records in a table by using the "UPDATE" statement:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley
345'"
mycursor.execute(sql)
mydb.commit()
USER:
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:
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')