Unit II
Console Input/Output
Console Input – Console Output – Formatted printing
Lists
Definition –– Operations – Methods – Varieties – Comprehension
Tuples
Definition – Accessing – Operations – Varieties – Comprehension – Conversion – Iterators and
Iterables – zip()
2.1 Console Input
In Python, console input refers to the process of getting input from the user via the
console or terminal during the program's execution. This is typically achieved using the input()
function.
Key Features of input():
1. Prompt Display: It optionally displays a prompt message to the user.
2. Data Type: By default, input() returns the user input as a string.
3. Conversion: If a different data type is needed (e.g., integer, float), the input must be
explicitly converted using type casting.
Syntax:
input([prompt])
• prompt: A string displayed to the user, often used to indicate what kind of input is
expected. It is optional.
Example 1: Basic Console Input
# Asking the user for their name
name = input("Enter your name: ")
print(f"Hello, {name}!")
Output:
Enter your name: Alice
Hello, Alice!
Example 2: Taking Numeric Input
# Calculating the sum of two numbers entered by the user
num1 = int(input("Enter the first number: "))
T. Karthikeyan. M.E (CSE), (Ph.D) 1
num2 = int(input("Enter the second number: "))
sum_result = num1 + num2
print(f"The sum of {num1} and {num2} is {sum_result}.")
Output:
Enter the first number: 10
Enter the second number: 20
The sum of 10 and 20 is 30.
2.2 Console Output
Console output in Python refers to displaying data or messages on the screen, typically
to provide feedback to the user or for debugging purposes. Python uses the print() function to
handle console output.
Characteristics of print() Function
• Syntax: print(*objects, sep=' ', end='\n', file=[Link], flush=False)
• Parameters:
o *objects: Any number of objects to be printed. They are converted to strings if
not already strings.
o sep: String inserted between the objects (default is a space ' ').
o end: String appended after the last object (default is a newline '\n').
o file: The file-like object to write to (default is [Link] for console output).
o flush: If True, forcibly flushes the stream.
Key Features
1. Simple Text Output: The print() function allows for outputting simple text messages.
2. Variable Output: Variables can be included in the print() statement to display their
values.
3. Formatted Output: Allows for formatting strings using methods like f-strings,
[Link](), or %.
Example Program: Console Output
# Example demonstrating console output in Python
# Printing simple messages
print("Welcome to Python Programming!")
# Printing variables
name = "Alice"
age = 25
T. Karthikeyan. M.E (CSE), (Ph.D) 2
print("Name:", name)
print("Age:", age)
# Using f-strings for formatted output
print(f"{name} is {age} years old.")
# Using sep and end parameters
print("Python", "is", "fun", sep="-", end="!\n")
# Printing multiple lines
print("Line 1\nLine 2\nLine 3")
Explanation of the Program
1. Simple Messages:
o "Welcome to Python Programming!" is printed as a string directly.
2. Variable Output:
o Variables name and age are printed with their values.
3. Formatted Output:
o The f-string f"{name} is {age} years old." embeds variables into the string.
4. Using sep and end:
o The sep="-" parameter inserts a dash between words.
o The end="!\n" parameter replaces the default newline with an exclamation mark
and a newline.
5. Multiple Lines:
o The \n escape character is used for new lines.
Output of the Program
Welcome to Python Programming!
Name: Alice
Age: 25
Alice is 25 years old.
Python-is-fun!
Line 1
Line 2
Line 3
T. Karthikeyan. M.E (CSE), (Ph.D) 3
2.3 Formatted printing
Formatted printing in Python refers to outputting strings and other data types in a
structured and readable manner. Python provides multiple ways to achieve formatted printing,
including:
1. Using the format() Method
2. Using f-strings
3. Using the % Operator
1. Using the format() Method
The format() method allows inserting values into a string using placeholders ({}), which can
be replaced with the corresponding values.
Example:
name = "Alice"
age = 25
height = 5.4
# Using format()
output = "My name is {}, I am {} years old, and I am {:.1f} feet tall.".format(name, age, height)
print(output)
Output:
My name is Alice, I am 25 years old, and I am 5.4 feet tall.
2. Using f-strings
F-strings, introduced in Python 3.6, are prefixed with f and allow embedding expressions inside
string literals using curly braces {}.
Example:
name = "Bob"
age = 30
height = 6.1
# Using f-strings
output = f"My name is {name}, I am {age} years old, and I am {height} feet tall."
print(output)
Output:
My name is Bob, I am 30 years old, and I am 6.1 feet tall.
3. Using the % Operator
T. Karthikeyan. M.E (CSE), (Ph.D) 4
The % operator is an older method that uses format specifiers (e.g., %s for strings, %d for
integers, %f for floating-point numbers).
Example:
name = "Charlie"
age = 22
height = 5.8
# Using % operator
print("My name is %s, I am %d years old, and I am %.1f feet tall." % (name, age, height))
Output:
My name is Charlie, I am 22 years old, and I am 5.8 feet tall.
Comprehensive Example Program
name = "Diana"
age = 28
salary = 75000.50
# Using format() method
output1 = "Employee Name: {}, Age: {}, Salary: ${:.2f}".format(name, age, salary)
# Using f-strings
output2 = f"Employee Name: {name}, Age: {age}, Salary: ${salary:.2f}"
# Using % operator
output3 = "Employee Name: %s, Age: %d, Salary: $%.2f" % (name, age, salary)
# Printing all outputs
print("Using format() method:")
print(output1)
print("\nUsing f-strings:")
print(output2)
print("\nUsing % operator:")
T. Karthikeyan. M.E (CSE), (Ph.D) 5
print(output3)
Output
Using format() method:
Employee Name: Diana, Age: 28, Salary: $75000.50
Using f-strings:
Employee Name: Diana, Age: 28, Salary: $75000.50
Using % operator:
Employee Name: Diana, Age: 28, Salary: $75000.50
Conclusion
Formatted printing in Python provides flexibility and power to display data in a structured
format. While format() and % are widely used, f-strings are preferred for their readability and
efficiency in modern Python versions.
2.4 Lists Definition & Accessing
A list in Python is a collection data type that is ordered, mutable (modifiable), and
allows duplicate elements. Lists are one of the most versatile and widely used data structures
in Python.
Lists are created by placing elements inside square brackets ([]), separated by commas.
Characteristics of Lists:
1. Ordered: Elements in a list maintain the order in which they are added.
2. Mutable: Elements can be added, removed, or changed.
3. Heterogeneous: A list can hold elements of different data types.
4. Indexing: Elements in a list can be accessed using their index, starting from 0 for the
first element.
Accessing List Elements
You can access elements of a list in the following ways:
1. Using Index: Access elements using their position in the list (0-based index).
2. Negative Indexing: Access elements from the end of the list using negative indices.
3. Slicing: Retrieve a subset of the list using a range of indices.
4. Iterating: Use loops to access elements one by one.
T. Karthikeyan. M.E (CSE), (Ph.D) 6
Example Program
# Define a list
my_list = [10, 20, 30, 40, 50, 'Hello', True]
# Accessing elements using positive index
print("Element at index 0:", my_list[0]) # Output: 10
print("Element at index 5:", my_list[5]) # Output: Hello
# Accessing elements using negative index
print("Element at index -1:", my_list[-1]) # Output: True
print("Element at index -3:", my_list[-3]) # Output: 40
# Slicing a list
print("Slice from index 1 to 4:", my_list[1:5]) # Output: [20, 30, 40, 50]
print("Slice from start to index 3:", my_list[:4]) # Output: [10, 20, 30, 40]
print("Slice from index 3 to end:", my_list[3:]) # Output: [40, 50, 'Hello', True]
# Iterating through the list
print("Iterating through the list:")
for item in my_list:
print(item)
# Modifying an element
my_list[2] = 35
print("List after modification:", my_list) # Output: [10, 20, 35, 40, 50, 'Hello', True]
Program Output
Element at index 0: 10
Element at index 5: Hello
Element at index -1: True
Element at index -3: 40
Slice from index 1 to 4: [20, 30, 40, 50]
Slice from start to index 3: [10, 20, 30, 40]
T. Karthikeyan. M.E (CSE), (Ph.D) 7
Slice from index 3 to end: [40, 50, 'Hello', True]
Iterating through the list:
10
20
30
40
50
Hello
True
List after modification: [10, 20, 35, 40, 50, 'Hello', True]
2.5 Lists Methods
Lists in Python are one of the most commonly used data structures. They are mutable,
ordered collections of items that can hold mixed data types (integers, strings, floats, etc.).
Python provides various methods to manipulate and work with lists effectively.
Below are the commonly used list methods, explained with examples:
1. append()
Adds a single element to the end of the list.
Example:
fruits = ['apple', 'banana', 'cherry']
[Link]('orange')
print(fruits)
Output:
['apple', 'banana', 'cherry', 'orange']
2. extend()
Extends the list by appending elements from another list (or any iterable).
Example:
fruits = ['apple', 'banana']
veggies = ['carrot', 'beans']
[Link](veggies)
print(fruits)
Output:
['apple', 'banana', 'carrot', 'beans']
T. Karthikeyan. M.E (CSE), (Ph.D) 8
3. insert()
Inserts an element at a specified index.
Example:
numbers = [1, 2, 4, 5]
[Link](2, 3)
print(numbers)
Output:
[1, 2, 3, 4, 5]
4. remove()
Removes the first occurrence of a specified value.
Example:
colors = ['red', 'green', 'blue', 'green']
[Link]('green')
print(colors)
Output:
['red', 'blue', 'green']
5. pop()
Removes and returns the element at the specified index. If no index is specified, it removes the
last item.
Example:
animals = ['cat', 'dog', 'rabbit']
last_animal = [Link]()
print(animals)
print("Removed animal:", last_animal)
Output:
['cat', 'dog']
Removed animal: rabbit
6. index()
Returns the index of the first occurrence of a specified value.
Example:
T. Karthikeyan. M.E (CSE), (Ph.D) 9
letters = ['a', 'b', 'c', 'a']
index_a = [Link]('a')
print("Index of 'a':", index_a)
Output:
Index of 'a': 0
7. count()
Returns the number of occurrences of a specified value in the list.
Example:
numbers = [1, 2, 2, 3, 2]
count_2 = [Link](2)
print("Count of 2:", count_2)
Output:
Count of 2: 3
8. sort()
Sorts the list in ascending order by default. It can take arguments like reverse=True for
descending order.
Example:
nums = [4, 1, 3, 2]
[Link]()
print("Ascending:", nums)
[Link](reverse=True)
print("Descending:", nums)
Output:
Ascending: [1, 2, 3, 4]
Descending: [4, 3, 2, 1]
9. reverse()
Reverses the order of the list.
Example:
alphabets = ['a', 'b', 'c', 'd']
[Link]()
print(alphabets)
T. Karthikeyan. M.E (CSE), (Ph.D) 10
Output:
['d', 'c', 'b', 'a']
10. copy()
Returns a shallow copy of the list.
Example:
original = [1, 2, 3]
duplicate = [Link]()
[Link](4)
print("Original:", original)
print("Duplicate:", duplicate)
Output:
Original: [1, 2, 3]
Duplicate: [1, 2, 3, 4]
11. clear()
Removes all elements from the list.
Example:
data = [10, 20, 30]
[Link]()
print(data)
Output:
[]
Complete Example Program
Here’s a program that demonstrates multiple list methods:
# List of students
students = ['Alice', 'Bob', 'Charlie']
# Adding a new student
[Link]('Diana')
print("After append:", students)
# Extending the list
T. Karthikeyan. M.E (CSE), (Ph.D) 11
[Link](['Eve', 'Frank'])
print("After extend:", students)
# Inserting a student at index 1
[Link](1, 'Grace')
print("After insert:", students)
# Removing a student
[Link]('Charlie')
print("After remove:", students)
# Pop the last student
removed_student = [Link]()
print("After pop:", students)
print("Removed student:", removed_student)
# Count occurrences of a name
count_eve = [Link]('Eve')
print("Count of 'Eve':", count_eve)
# Sorting students alphabetically
[Link]()
print("After sort:", students)
# Reversing the list
[Link]()
print("After reverse:", students)
# Copying the list
new_list = [Link]()
print("Copied list:", new_list)
# Clearing the list
[Link]()
T. Karthikeyan. M.E (CSE), (Ph.D) 12
print("After clear:", students)
Output of the Program
After append: ['Alice', 'Bob', 'Charlie', 'Diana']
After extend: ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
After insert: ['Alice', 'Grace', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
After remove: ['Alice', 'Grace', 'Bob', 'Diana', 'Eve', 'Frank']
After pop: ['Alice', 'Grace', 'Bob', 'Diana', 'Eve']
Removed student: Frank
Count of 'Eve': 1
After sort: ['Alice', 'Bob', 'Diana', 'Eve', 'Grace']
After reverse: ['Grace', 'Eve', 'Diana', 'Bob', 'Alice']
Copied list: ['Grace', 'Eve', 'Diana', 'Bob', 'Alice']
After clear: []
2.6 Lists Varieties
In Python, a list is a versatile and mutable data structure that can store a collection of
items. These items can be of different types (integers, strings, floats, or even other lists). Lists
are defined by enclosing their elements in square brackets [ ].
Varieties of Lists in Python
1. Empty List:
o A list with no elements.
o Example: empty_list = []
2. Homogeneous List:
o Contains elements of the same type.
o Example: num_list = [1, 2, 3, 4, 5]
3. Heterogeneous List:
o Contains elements of different types.
o Example: mixed_list = [1, "Python", 3.14, True]
4. Nested List:
o A list within a list.
o Example: nested_list = [[1, 2], [3, 4], [5, 6]]
5. Dynamic List:
T. Karthikeyan. M.E (CSE), (Ph.D) 13
o Lists can be modified (add, remove, or update elements).
o Example:
o dynamic_list = [1, 2, 3]
o dynamic_list.append(4) # Add an element
o dynamic_list[1] = 10 # Update an element
Example Program
# Demonstrating different varieties of lists
# 1. Empty List
empty_list = []
print("Empty List:", empty_list)
# 2. Homogeneous List
homogeneous_list = [10, 20, 30, 40]
print("Homogeneous List:", homogeneous_list)
# 3. Heterogeneous List
heterogeneous_list = [25, "Hello", 3.14, False]
print("Heterogeneous List:", heterogeneous_list)
# 4. Nested List
nested_list = [[1, 2, 3], [4, 5, 6], ["a", "b", "c"]]
print("Nested List:", nested_list)
# 5. Dynamic List
dynamic_list = [1, 2, 3]
print("Original Dynamic List:", dynamic_list)
dynamic_list.append(4) # Adding an element
print("After Append:", dynamic_list)
dynamic_list[0] = 100 # Updating an element
print("After Update:", dynamic_list)
dynamic_list.remove(2) # Removing an element
print("After Removal:", dynamic_list)
T. Karthikeyan. M.E (CSE), (Ph.D) 14
Output
Empty List: []
Homogeneous List: [10, 20, 30, 40]
Heterogeneous List: [25, 'Hello', 3.14, False]
Nested List: [[1, 2, 3], [4, 5, 6], ['a', 'b', 'c']]
Original Dynamic List: [1, 2, 3]
After Append: [1, 2, 3, 4]
After Update: [100, 2, 3, 4]
After Removal: [100, 3, 4]
Key Features of Python Lists
1. Order Maintained: Elements are stored in the order they are added.
2. Indexing: Elements can be accessed using indices, starting from 0.
3. Mutable: Lists can be modified after creation.
4. Dynamic: No need to specify size beforehand; it grows or shrinks dynamically.
5. Versatile: Supports slicing, iteration, and multiple methods like append(), extend(),
pop(), and remove().
2.7 Lists Comprehension
List comprehension is a concise way to create lists in Python. It offers a shorter syntax
for creating a new list based on the values of an existing iterable (like a list, range, or another
sequence). It is not only more readable but also more efficient compared to using traditional
loops and append() methods.
Syntax of List Comprehension
[expression for item in iterable if condition]
• expression: The operation or transformation applied to each item.
• item: The variable that takes the value of each element in the iterable.
• iterable: The sequence or collection you are iterating over.
• if condition (optional): A filter that includes elements in the new list only if the
condition is True.
Advantages of List Comprehension
1. Compactness: Reduces the number of lines of code.
2. Readability: Easier to understand once familiar with the syntax.
T. Karthikeyan. M.E (CSE), (Ph.D) 15
3. Efficiency: Generally faster than using loops with append().
Examples with Explanation
1. Basic Example: Creating a List of Squares
# Traditional approach
squares = []
for x in range(10):
[Link](x ** 2)
# Using list comprehension
squares = [x ** 2 for x in range(10)]
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Explanation:
• The expression x ** 2 calculates the square of each number.
• The range(10) provides numbers from 0 to 9.
2. Adding a Condition
Create a list of even numbers from 0 to 9.
# Traditional approach
evens = []
for x in range(10):
if x % 2 == 0:
[Link](x)
# Using list comprehension
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Output:
[0, 2, 4, 6, 8]
Explanation:
• The condition x % 2 == 0 ensures only even numbers are included.
T. Karthikeyan. M.E (CSE), (Ph.D) 16
3. Nested Loops in List Comprehension
Create a list of pairs (x, y) where x is from 1 to 3 and y is from 4 to 6.
# Traditional approach
pairs = []
for x in range(1, 4):
for y in range(4, 7):
[Link]((x, y))
# Using list comprehension
pairs = [(x, y) for x in range(1, 4) for y in range(4, 7)]
print(pairs)
Output:
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Explanation:
• Two for loops are nested in the list comprehension.
4. Using Functions in List Comprehension
Convert a list of temperatures in Celsius to Fahrenheit.
# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
# List of Celsius temperatures
celsius = [0, 10, 20, 30, 40]
# Using list comprehension
fahrenheit = [celsius_to_fahrenheit(temp) for temp in celsius]
print(fahrenheit)
Output:
[32.0, 50.0, 68.0, 86.0, 104.0]
Explanation:
• The function celsius_to_fahrenheit() is called for each element in the celsius list.
Nested Example Program
T. Karthikeyan. M.E (CSE), (Ph.D) 17
Create a list of numbers that are squares of even numbers from 0 to 19.
# Traditional approach
squares_of_evens = []
for x in range(20):
if x % 2 == 0:
squares_of_evens.append(x ** 2)
# Using list comprehension
squares_of_evens = [x ** 2 for x in range(20) if x % 2 == 0]
print(squares_of_evens)
Output:
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
2.8 Tuples Definition & Accessing
A tuple in Python is an immutable, ordered collection of items. It is similar to a list but
differs in that tuples cannot be modified after their creation. Tuples are used to group related
data, ensuring that the elements remain constant throughout the program.
• Tuples are defined using parentheses ().
• They can contain elements of different data types (e.g., integers, strings, floats, etc.).
• Tuples support indexing and slicing like lists.
Key Characteristics
1. Immutable: Elements in a tuple cannot be changed or modified.
2. Ordered: The order of elements is preserved.
3. Allows Duplicates: Duplicate elements are allowed in a tuple.
Creating a Tuple
A tuple can be created in several ways:
• Using parentheses: tuple1 = (1, 2, 3)
• Without parentheses (comma-separated values): tuple2 = 1, 2, 3
• Using the tuple() constructor: tuple3 = tuple([1, 2, 3])
Accessing Tuple Elements
Since tuples are ordered, elements can be accessed:
1. By Index: Using square brackets [ ]. Indexing starts at 0.
T. Karthikeyan. M.E (CSE), (Ph.D) 18
2. Negative Indexing: Negative indices start from -1 (last element).
3. Slicing: Using : to access a subset of elements.
Example Program
# Defining a tuple
fruits = ("apple", "banana", "cherry", "date", "fig")
# Accessing elements by index
print("First fruit:", fruits[0]) # Access the first element
print("Last fruit:", fruits[-1]) # Access the last element
# Slicing a tuple
print("First three fruits:", fruits[:3]) # Slicing first three elements
# Nested tuple
nested_tuple = ("orange", (1, 2, 3), ["grape", "melon"])
print("Nested tuple:", nested_tuple)
print("Accessing inner tuple:", nested_tuple[1]) # Access inner tuple
print("Accessing element of inner tuple:", nested_tuple[1][2]) # Element in inner tuple
# Length of tuple
print("Length of the tuple:", len(fruits))
# Checking membership
print("Is 'apple' in the tuple?", "apple" in fruits)
print("Is 'kiwi' in the tuple?", "kiwi" in fruits)
Expected Output
First fruit: apple
Last fruit: fig
First three fruits: ('apple', 'banana', 'cherry')
Nested tuple: ('orange', (1, 2, 3), ['grape', 'melon'])
Accessing inner tuple: (1, 2, 3)
Accessing element of inner tuple: 3
T. Karthikeyan. M.E (CSE), (Ph.D) 19
Length of the tuple: 5
Is 'apple' in the tuple? True
Is 'kiwi' in the tuple? False
Explanation of the Code
1. Access by Index: Demonstrates how to fetch elements using positive and negative
indices.
2. Slicing: Extracts a portion of the tuple.
3. Nested Tuples: Shows tuples within tuples and accessing nested elements.
4. Length: Using len() to find the number of elements.
5. Membership Testing: Using in to check if an element exists in the tuple.
Advantages of Tuples
1. Immutability ensures data integrity.
2. Memory Efficient compared to lists.
3. Useful for representing fixed collections like days of the week or coordinates.
2.9 Tuples Operations
A tuple is an immutable sequence in Python, used to store a collection of items. Tuples
are ordered, can contain duplicate items, and can hold elements of different data types. Once a
tuple is created, its elements cannot be modified.
Tuple Operations in Python
1. Creating Tuples
Tuples can be created by enclosing items in parentheses () separated by commas.
# Creating tuples
tuple1 = (1, 2, 3, 4)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (1, "apple", True)
2. Accessing Elements
Tuples support indexing to access individual elements.
# Accessing elements
tuple1 = (10, 20, 30, 40)
print(tuple1[0]) # Output: 10
print(tuple1[-1]) # Output: 40
T. Karthikeyan. M.E (CSE), (Ph.D) 20
3. Slicing
You can extract a subset of a tuple using slicing.
# Slicing
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[1:4]) # Output: (2, 3, 4)
4. Concatenation
You can combine two tuples using the + operator.
# Concatenation
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
5. Repetition
You can repeat the elements of a tuple using the * operator.
# Repetition
tuple1 = (1, 2)
result = tuple1 * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
6. Membership Testing
Check whether an element exists in a tuple using in and not in.
# Membership Testing
tuple1 = (1, 2, 3)
print(2 in tuple1) # Output: True
print(5 not in tuple1) # Output: True
7. Length of a Tuple
The len() function returns the number of elements in a tuple.
# Length of Tuple
tuple1 = (1, 2, 3)
print(len(tuple1)) # Output: 3
8. Iterating Through Tuples
You can iterate through tuples using loops.
# Iteration
tuple1 = (1, 2, 3)
for item in tuple1:
T. Karthikeyan. M.E (CSE), (Ph.D) 21
print(item)
9. Tuple Methods
Tuples have two methods: count() and index().
• count(value): Counts occurrences of a value.
• index(value): Returns the index of the first occurrence of a value.
# Tuple Methods
tuple1 = (1, 2, 3, 1)
print([Link](1)) # Output: 2
print([Link](2)) # Output: 1
10. Tuple Unpacking
You can unpack tuple elements into variables.
# Unpacking
tuple1 = (1, 2, 3)
a, b, c = tuple1
print(a, b, c) # Output: 1 2 3
Example Program: Tuple Operations
# Example Program
# Define a tuple
fruits = ("apple", "banana", "cherry", "apple", "cherry")
# Accessing elements
print("First element:", fruits[0])
print("Last element:", fruits[-1])
# Slicing
print("Sliced tuple:", fruits[1:4])
# Concatenation
vegetables = ("carrot", "potato")
combined = fruits + vegetables
print("Combined tuple:", combined)
# Repetition
T. Karthikeyan. M.E (CSE), (Ph.D) 22
print("Repeated tuple:", fruits * 2)
# Membership testing
print("Is 'apple' in fruits?", "apple" in fruits)
# Count and Index methods
print("Count of 'apple':", [Link]("apple"))
print("Index of 'banana':", [Link]("banana"))
# Length
print("Length of tuple:", len(fruits))
# Iterating through tuple
print("Iterating through tuple:")
for item in fruits:
print(item)
Output:
First element: apple
Last element: cherry
Sliced tuple: ('banana', 'cherry', 'apple')
Combined tuple: ('apple', 'banana', 'cherry', 'apple', 'cherry', 'carrot', 'potato')
Repeated tuple: ('apple', 'banana', 'cherry', 'apple', 'cherry', 'apple', 'banana', 'cherry', 'apple',
'cherry')
Is 'apple' in fruits? True
Count of 'apple': 2
Index of 'banana': 1
Length of tuple: 5
Iterating through tuple:
apple
banana
cherry
apple
cherry
T. Karthikeyan. M.E (CSE), (Ph.D) 23
2.10 Tuples Varieties
In Python, a tuple is an immutable ordered collection of elements. Tuples can hold
elements of different data types, and their immutability ensures that the elements cannot be
changed after the tuple is created. Here's a detailed explanation of tuple varieties with
examples.
1. Empty Tuple
An empty tuple is a tuple with no elements.
empty_tuple = ()
print("Empty Tuple:", empty_tuple)
Output:
Empty Tuple: ()
2. Tuple with Single Element
A tuple with one element must include a trailing comma to distinguish it from a regular variable.
single_tuple = (42,)
print("Single Element Tuple:", single_tuple)
Output:
Single Element Tuple: (42,)
3. Tuple with Multiple Elements
A tuple can contain multiple elements of different data types.
multi_tuple = (1, "Python", 3.14)
print("Multiple Elements Tuple:", multi_tuple)
Output:
Multiple Elements Tuple: (1, 'Python', 3.14)
4. Nested Tuple
A tuple can contain other tuples as elements, creating a nested structure.
nested_tuple = (1, (2, 3), (4, (5, 6)))
print("Nested Tuple:", nested_tuple)
Output:
Nested Tuple: (1, (2, 3), (4, (5, 6)))
T. Karthikeyan. M.E (CSE), (Ph.D) 24
5. Tuple with Mixed Data Types
A tuple can hold integers, floats, strings, and even lists or dictionaries.
mixed_tuple = (42, "Hello", [1, 2, 3], {"key": "value"})
print("Mixed Data Types Tuple:", mixed_tuple)
Output:
Mixed Data Types Tuple: (42, 'Hello', [1, 2, 3], {'key': 'value'})
6. Tuple Packing and Unpacking
Packing refers to combining multiple values into a tuple, while unpacking extracts those values
into variables.
# Tuple Packing
packed_tuple = 1, 2, 3
print("Packed Tuple:", packed_tuple)
# Tuple Unpacking
a, b, c = packed_tuple
print("Unpacked Values:", a, b, c)
Output:
Packed Tuple: (1, 2, 3)
Unpacked Values: 1 2 3
7. Tuple Operations
Python supports several operations on tuples, including indexing, slicing, and concatenation.
sample_tuple = (10, 20, 30, 40, 50)
# Indexing
print("Element at Index 2:", sample_tuple[2])
# Slicing
print("Sliced Tuple:", sample_tuple[1:4])
# Concatenation
new_tuple = sample_tuple + (60, 70)
T. Karthikeyan. M.E (CSE), (Ph.D) 25
print("Concatenated Tuple:", new_tuple)
Output:
Element at Index 2: 30
Sliced Tuple: (20, 30, 40)
Concatenated Tuple: (10, 20, 30, 40, 50, 60, 70)
8. Immutability of Tuples
Tuples are immutable, meaning their elements cannot be changed after creation.
immutable_tuple = (1, 2, 3)
try:
immutable_tuple[1] = 42
except TypeError as e:
print("Error:", e)
Output:
Error: 'tuple' object does not support item assignment
9. Using Tuples in Functions
Tuples are often used to return multiple values from functions.
def return_multiple():
return 1, 2, 3
result = return_multiple()
print("Returned Tuple:", result)
Output:
Returned Tuple: (1, 2, 3)
10. Advantages of Tuples
1. Immutability: Tuples ensure data integrity.
2. Hashable: Tuples can be used as keys in dictionaries, unlike lists.
3. Memory Efficiency: Tuples consume less memory compared to lists.
Summary Example
Below is a complete example showcasing various tuple varieties:
# Various Tuple Varieties
T. Karthikeyan. M.E (CSE), (Ph.D) 26
empty_tuple = ()
single_tuple = (42,)
multi_tuple = (1, "Python", 3.14)
nested_tuple = (1, (2, 3), (4, (5, 6)))
mixed_tuple = (42, "Hello", [1, 2, 3], {"key": "value"})
# Tuple Operations
packed_tuple = 1, 2, 3
a, b, c = packed_tuple
# Function Returning Tuple
def sample_function():
return "A", "B", "C"
returned_tuple = sample_function()
# Print All
print(f"Empty Tuple: {empty_tuple}")
print(f"Single Element Tuple: {single_tuple}")
print(f"Multiple Elements Tuple: {multi_tuple}")
print(f"Nested Tuple: {nested_tuple}")
print(f"Mixed Tuple: {mixed_tuple}")
print(f"Packed Tuple: {packed_tuple}, Unpacked Values: {a}, {b}, {c}")
print(f"Returned Tuple from Function: {returned_tuple}")
Output:
Empty Tuple: ()
Single Element Tuple: (42,)
Multiple Elements Tuple: (1, 'Python', 3.14)
Nested Tuple: (1, (2, 3), (4, (5, 6)))
Mixed Tuple: (42, 'Hello', [1, 2, 3], {'key': 'value'})
Packed Tuple: (1, 2, 3), Unpacked Values: 1, 2, 3
Returned Tuple from Function: ('A', 'B', 'C')
T. Karthikeyan. M.E (CSE), (Ph.D) 27
2.11 Tuples Comprehension
In Python, tuples comprehension refers to a concise and efficient way of generating
tuples using a similar syntax to list comprehensions. However, unlike lists, tuples are
immutable. This means that once created, their elements cannot be changed. Tuples
comprehension allows you to create tuples based on an expression, optionally with an if
condition.
Syntax:
The syntax for tuple comprehension is similar to list comprehension, but it is wrapped in
parentheses () instead of square brackets []:
(tuple_expression for item in iterable if condition)
Here:
• tuple_expression: The expression or operation you want to perform on each element of
the iterable.
• iterable: The iterable object (like a list or range) you are looping over.
• condition: An optional condition that filters which elements to include in the resulting
tuple.
Important Points:
1. Tuples are immutable: Once created, the elements in a tuple cannot be modified.
2. Tuples comprehension does not exist directly: Python doesn't support tuples
comprehension in the same way as lists. Instead, we use a generator expression inside
the tuple() function to create tuples.
Example Program:
Program to generate a tuple of squares of even numbers from a given list using tuple
comprehension:
# Sample list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using tuple comprehension (with a generator expression inside tuple())
squares_of_even_numbers = tuple(x**2 for x in numbers if x % 2 == 0)
# Output the result
print(squares_of_even_numbers)
Explanation:
• numbers: A list containing numbers from 1 to 10.
T. Karthikeyan. M.E (CSE), (Ph.D) 28
• The expression x**2 computes the square of each number.
• The if x % 2 == 0 condition ensures that only even numbers are considered.
• The tuple() function converts the generator expression into a tuple.
Output:
(4, 16, 36, 64, 100)
Step-by-Step Breakdown:
1. The program iterates through the list numbers.
2. It checks if the number is even using the condition x % 2 == 0.
3. If the condition is true, it calculates the square of the number (x**2).
4. Finally, the generator expression generates the values, which are then wrapped into a
tuple.
Another Example Program:
Program to generate a tuple of cubes of numbers greater than 5 from a given list:
# Sample list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Tuple comprehension to find the cube of numbers greater than 5
cubes_of_numbers = tuple(x**3 for x in numbers if x > 5)
# Output the result
print(cubes_of_numbers)
Output:
(216, 343, 512, 729)
Explanation:
• Here, the program only processes numbers greater than 5 (if x > 5).
• It calculates their cubes (x**3) and returns the result as a tuple.
2.12 Tuples Conversion
In Python, tuples are immutable sequences of values, often used to store heterogeneous
data. Since tuples are immutable, they do not allow modification of their content once created.
However, conversion between different data types, such as lists and tuples, is a common
operation. This conversion allows the flexibility to utilize the properties of both lists and tuples
as needed.
T. Karthikeyan. M.E (CSE), (Ph.D) 29
Types of Tuples Conversion
1. List to Tuple Conversion:
o A list is a mutable sequence, and a tuple is immutable. You can convert a list
into a tuple using the tuple() function.
2. Tuple to List Conversion:
o You can convert a tuple into a list using the list() function.
3. Tuple to Set Conversion:
o You can convert a tuple into a set, which is an unordered collection without
duplicate elements, using the set() function.
4. Set to Tuple Conversion:
o A set can be converted into a tuple by using the tuple() function.
Conversion Examples and Explanation
Let’s look at each of these conversions in detail.
Example Program
# List to Tuple Conversion
list_data = [1, 2, 3, 4, 5]
tuple_data = tuple(list_data)
print("List to Tuple Conversion:")
print("Original List:", list_data)
print("Converted Tuple:", tuple_data)
# Tuple to List Conversion
tuple_data = (1, 2, 3, 4, 5)
list_data = list(tuple_data)
print("\nTuple to List Conversion:")
print("Original Tuple:", tuple_data)
print("Converted List:", list_data)
# Tuple to Set Conversion
tuple_data = (1, 2, 3, 4, 5, 1, 2)
set_data = set(tuple_data)
print("\nTuple to Set Conversion:")
print("Original Tuple:", tuple_data)
print("Converted Set:", set_data)
T. Karthikeyan. M.E (CSE), (Ph.D) 30
# Set to Tuple Conversion
set_data = {1, 2, 3, 4, 5, 1, 2}
tuple_data = tuple(set_data)
print("\nSet to Tuple Conversion:")
print("Original Set:", set_data)
print("Converted Tuple:", tuple_data)
Explanation of Code:
1. List to Tuple Conversion:
o A list list_data = [1, 2, 3, 4, 5] is converted into a tuple using the tuple() function.
This results in the tuple (1, 2, 3, 4, 5).
2. Tuple to List Conversion:
o A tuple tuple_data = (1, 2, 3, 4, 5) is converted into a list using the list() function.
This results in the list [1, 2, 3, 4, 5].
3. Tuple to Set Conversion:
o A tuple tuple_data = (1, 2, 3, 4, 5, 1, 2) is converted into a set using the set()
function. Since sets do not allow duplicate values, the duplicates 1 and 2 are
removed, resulting in the set {1, 2, 3, 4, 5}.
4. Set to Tuple Conversion:
o A set set_data = {1, 2, 3, 4, 5, 1, 2} is converted back into a tuple using the
tuple() function. The resulting tuple contains the elements in an arbitrary order
because sets are unordered collections. Thus, the tuple might look like (1, 2, 3,
4, 5).
Output:
List to Tuple Conversion:
Original List: [1, 2, 3, 4, 5]
Converted Tuple: (1, 2, 3, 4, 5)
Tuple to List Conversion:
Original Tuple: (1, 2, 3, 4, 5)
Converted List: [1, 2, 3, 4, 5]
Tuple to Set Conversion:
Original Tuple: (1, 2, 3, 4, 5, 1, 2)
T. Karthikeyan. M.E (CSE), (Ph.D) 31
Converted Set: {1, 2, 3, 4, 5}
Set to Tuple Conversion:
Original Set: {1, 2, 3, 4, 5}
Converted Tuple: (1, 2, 3, 4, 5)
2.13 Tuples Iterators and Iterables
1. Tuples in Python
A tuple is a collection of ordered elements, similar to a list, but unlike lists, tuples are
immutable, meaning their elements cannot be modified once they are created. Tuples are
defined using parentheses ().
Example:
# Defining a tuple
my_tuple = (10, 20, 30, 40)
# Accessing elements of a tuple
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
Output:
First element: 10
Last element: 40
2. Iterators in Python
An iterator in Python is an object that allows traversing through a sequence (like a tuple) one
element at a time. To be an iterator, an object must implement two methods:
• __iter__(): This method returns the iterator object itself.
• __next__(): This method returns the next element in the sequence. When there are no
more elements, it raises the StopIteration exception.
Example of an iterator with a tuple:
# Creating an iterator for a tuple
my_tuple = (10, 20, 30, 40)
tuple_iterator = iter(my_tuple)
# Using the iterator to access elements
print(next(tuple_iterator)) # 10
T. Karthikeyan. M.E (CSE), (Ph.D) 32
print(next(tuple_iterator)) # 20
print(next(tuple_iterator)) # 30
print(next(tuple_iterator)) # 40
# Uncommenting the line below would raise StopIteration error
# print(next(tuple_iterator))
Output:
10
20
30
40
After accessing the last element, calling next() again would raise a StopIteration error,
indicating that there are no more elements in the tuple.
3. Iterable in Python
An iterable is any Python object capable of returning its members one at a time, permitting it
to be iterated over in a for-loop. A tuple is inherently iterable, as it can return an iterator when
passed to the iter() function.
Example of iterating over a tuple using a for-loop:
# Iterating over a tuple
my_tuple = (10, 20, 30, 40)
for element in my_tuple:
print(element)
Output:
10
20
30
40
In this example, the tuple my_tuple is an iterable, and using a for loop automatically calls the
iter() method and the next() method in the background to traverse through each element.
4. Combination of Tuples, Iterators, and Iterables
We can combine tuples, iterators, and iterables effectively. For example, we can create an
iterator from a tuple and manually traverse through it or use a for loop to iterate through the
tuple directly.
T. Karthikeyan. M.E (CSE), (Ph.D) 33
Example: Manually using next() to traverse and using a for loop:
# Creating a tuple and converting it to an iterator
my_tuple = (1, 2, 3, 4, 5)
iterator = iter(my_tuple)
# Manual iteration using next()
print(next(iterator)) # 1
print(next(iterator)) # 2
# Iterating using a for loop
for value in iterator:
print(value)
Output:
1
2
3
4
5
Explanation:
• The first two next() calls access the first two elements (1, 2) of the tuple.
• The for loop then iterates over the remaining elements, automatically using the next()
function internally.
2.14 Tuples zip()
The zip() function in Python is a built-in function that combines multiple iterables (like
lists, tuples, etc.) element by element into a single iterable. It returns an iterator of tuples, where
each tuple contains elements from each of the passed iterables at the corresponding position. If
the input iterables have unequal lengths, the zip function stops creating tuples when the shortest
iterable is exhausted.
Syntax:
zip(iterable1, iterable2, ...)
• iterable1, iterable2, ...: These are the iterables (lists, tuples, etc.) that you want to zip
together.
T. Karthikeyan. M.E (CSE), (Ph.D) 34
Key Points:
1. The resulting object is a zip object, which is an iterator.
2. You can convert the result to a list, tuple, or any other collection type.
3. If the input iterables have unequal lengths, zip() stops when the shortest iterable is
exhausted.
Example 1: Basic Example with Tuples
Here’s an example program to demonstrate how the zip() function works with tuples:
# Example of zipping two tuples
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
# Using zip to combine the two tuples
zipped = zip(tuple1, tuple2)
# Converting the result to a list and printing it
zipped_list = list(zipped)
print(zipped_list)
Output:
[(1, 'a'), (2, 'b'), (3, 'c')]
Explanation:
In the above example, the zip() function combines the two tuples, tuple1 and tuple2, element
by element:
• The first elements (1, 'a') are zipped together.
• The second elements (2, 'b') are zipped together.
• The third elements (3, 'c') are zipped together. This results in a list of tuples, where each
tuple contains elements from the corresponding positions of tuple1 and tuple2.
Example 2: Handling Unequal Lengths
If the input iterables are of unequal lengths, zip() stops when the shortest iterable is exhausted.
# Example with unequal lengths
tuple1 = (1, 2, 3, 4)
tuple2 = ('a', 'b', 'c')
# Zipping the tuples
zipped = zip(tuple1, tuple2)
T. Karthikeyan. M.E (CSE), (Ph.D) 35
# Converting to a list and printing
zipped_list = list(zipped)
print(zipped_list)
Output:
[(1, 'a'), (2, 'b'), (3, 'c')]
Explanation:
In this case, tuple1 has 4 elements, and tuple2 has only 3 elements. The zip() function combines
elements until the shortest tuple is exhausted, so the fourth element of tuple1 (which is 4) is
ignored, and the output stops after (3, 'c').
Example 3: Zipping Multiple Iterables
You can zip more than two iterables together. Here's an example with three tuples:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
tuple3 = ('apple', 'banana', 'cherry')
# Zipping three tuples
zipped = zip(tuple1, tuple2, tuple3)
# Converting to a list and printing
zipped_list = list(zipped)
print(zipped_list)
Output:
[(1, 'a', 'apple'), (2, 'b', 'banana'), (3, 'c', 'cherry')]
Explanation:
Here, zip() combines elements from all three tuples into a tuple of three elements each:
• (1, 'a', 'apple')
• (2, 'b', 'banana')
• (3, 'c', 'cherry')
Example 4: Unzipping
You can also "unzip" a zipped object using the zip() function combined with the unpacking
operator *. This splits the zipped object back into separate iterables.
# Zipping two lists
tuple1 = (1, 2, 3)
T. Karthikeyan. M.E (CSE), (Ph.D) 36
tuple2 = ('a', 'b', 'c')
zipped = zip(tuple1, tuple2)
# Unzipping the tuples
unzipped = zip(*zipped)
# Converting to lists and printing
unzipped_list = list(unzipped)
print(unzipped_list)
Output:
[(1, 2, 3), ('a', 'b', 'c')]
Explanation:
In this example, we first zip two tuples, and then use the unpacking operator * to unzip the list
of tuples into two separate lists.
Use Cases of zip():
1. Parallel Iteration: When you need to iterate over two or more iterables in parallel.
2. Pairing Data: When you want to combine two lists into a dictionary or other paired
structures.
3. Matrix Transposition: You can use zip() to transpose a matrix (convert rows to
columns and vice versa).
Example 5: Pairing Data into a Dictionary
keys = ('name', 'age', 'location')
values = ('Alice', 30, 'New York')
# Zipping keys and values to create a dictionary
zipped = zip(keys, values)
result = dict(zipped)
# Printing the dictionary
print(result)
Output:
{'name': 'Alice', 'age': 30, 'location': 'New York'}
T. Karthikeyan. M.E (CSE), (Ph.D) 37