0% found this document useful (0 votes)
12 views110 pages

Unit Iii

This document provides a comprehensive overview of lists in Python, detailing their characteristics as ordered, mutable data structures that can contain various data types. It covers how to create, access, modify, and traverse lists, as well as operations such as slicing, filtering, and using built-in functions like map() and reduce(). Additionally, it highlights the differences between lists and other sequence types, and explains the concept of objects and values in Python.

Uploaded by

pragadasairam5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views110 pages

Unit Iii

This document provides a comprehensive overview of lists in Python, detailing their characteristics as ordered, mutable data structures that can contain various data types. It covers how to create, access, modify, and traverse lists, as well as operations such as slicing, filtering, and using built-in functions like map() and reduce(). Additionally, it highlights the differences between lists and other sequence types, and explains the concept of objects and values in Python.

Uploaded by

pragadasairam5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

UNIT-III

Lists in
Python
List
• In Python, a list is a widely used data structure that allows you to store
multiple items in a single variable.

• Lists are ordered, mutable (changeable), and can contain elements of


different data types, including other lists.

How to Create a List


Lists are defined using square brackets [], with elements separated
by commas:
Example
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, 3.14, True]
empty = []
Accessing List Elements
You can access elements by their index (starting from 0):​

print(fruits[0]) # Output: apple


print(fruits[-1]) # Output: cherry (last item)
print(fruits[1:3]) # Output: ['banana', 'cherry']
Modifying Lists
• Lists are mutable, allowing you to change their content:

fruits[1] = "blueberry" # Modify element


fruits.append("orange") # Add to end
fruits.insert(1, "kiwi") # Insert at position
fruits.remove("apple") # Remove by value
last = fruits.pop() # Remove last item
List Comprehensions
• List comprehensions provide a concise way to create lists:​

squares = [x**2 for x in range(5)]


# [0, 1, 4, 9, 16]

evens = [x for x in range(10) if x % 2 == 0]


# [0, 2, 4, 6, 8]
Nested Lists
• Lists can contain other lists, allowing for the creation of multi-dimensional

structures:​

• This method of accessing elements is known as nested indexing, where you

first select a sublist (row) and then an element within that sublist (column).

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2])
Iterating Over Lists
• You can loop through lists using for loops:​

for fruit in fruits:


print(fruit)

• To access both index and value, use enumerate():

for index, fruit in enumerate(fruits):


print(index, fruit)
List sequence
• In Python, a list is a type of sequence, which is an ordered collection of items. Sequences allow you to store

multiple values in a single variable and access them using indexing.

• What Is a Sequence?

A sequence in Python is an iterable data structure that maintains the order of its elements. This means

you can access elements by their position (index) in the sequence. Common sequence types include:

• Lists: Mutable sequences that can contain elements of different types.

• Tuples: Immutable sequences, meaning their elements cannot be changed after creation.

• Strings: Sequences of characters.​

• All sequences support operations like indexing, slicing, and iteration.


Lists as Sequences
• A list is a versatile and widely used sequence type in Python. Lists are
mutable, allowing you to modify their contents after creation.
• They can contain elements of any data type, including other lists.​

my_list = [10, 'hello', 3.14, [1, 2, 3]]

• Lists support various operations such as appending, inserting,


removing elements, and more. ​
Creating Sequences
• You can create sequences in several ways:​

• Using range(): Generates a sequence of numbers.

• numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]

• squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]


Lists are mutable

• ​In Python, lists are mutable, meaning you can change their content after
creation without altering their identity. This includes modifying elements,
adding new items, or removing existing ones.

• A mutable object allows its internal state or contents to be changed. In


contrast, an immutable object does not permit any alteration after its
creation.
Examples of List Mutability
• Modifying Elements by Index: You can change the value of an existing
element in a list by accessing it through its index:​

my_list = [1, 2, 3]
my_list[0] = 10
print(my_list)

# Output: [10, 2, 3]
Adding Elements
• Using append(): Adds a single element to the end of the list.

my_list.append(4)
print(my_list)

# Output: [10, 2, 3, 4]
Removing Elements
• Using remove(): Removes the first occurrence of a specified value.​

my_list.remove(2)
print(my_list)

# Output: [10, 3, 4, 5, 6]
Mutable vs. Immutable Types in
Python
Mutable Types Immutable Types
list int, float
dict str
set tuple
Custom class frozenset
objects
Traversing a List
• ​Traversing a list in Python means accessing each element in the list,
one by one, to perform operations such as printing, modifying, or
applying functions

• Python offers several methods to traverse lists, each suited for


different scenarios.​
1. Using a for Loop
• The most straightforward way to traverse a list is by using a for loop,
which accesses each element directly:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

• This method is ideal when you need to read or process each item in
the list.
2. Using for Loop with range()
and len()
• When you need to access both the index and the value, combining
range() with len() is effective:

fruits = ["apple", "banana", "cherry"]


for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")

• This approach is useful when the position of each element is


significant.
3. Using enumerate()
• The enumerate() function provides a cleaner way to access both index
and value:

fruits = ["apple", "banana", "cherry"]


for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")

• This method enhances readability and is preferred over using range()


with len() when both index and value are needed.
4. Using a while Loop
• A while loop offers more control, especially when the traversal needs
to be conditional:

fruits = ["apple", "banana", "cherry"]


i=0
while i < len(fruits):
print(fruits[i])
i += 1
• This method is beneficial when the loop's continuation depends on
dynamic conditions.
5. Using List Comprehension
• List comprehensions provide a concise way to traverse and process lists:

fruits = ["apple", "banana", "cherry"]


[print(fruit.upper()) for fruit in fruits]

This approach is suitable for simple operations and can make the code
more readable.
6. Traversing Nested Lists
• For lists containing sublists, nested loops are necessary:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item, end=' ‘)
This method allows you to access each element within the nested lists.
7. Using zip() to Traverse
Multiple Lists
• When you need to traverse multiple lists simultaneously, zip() is
useful:

names = ["Alice", "Bob", "Charlie"]


scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")

This approach pairs elements from each list together, facilitating


parallel traversal.
List operations
• ​In Python, lists are versatile and come with a variety of built-in
operations and methods that allow you to manipulate and interact
with them effectively.
• Here's an overview of common list operations:​

• Adding Elements
• Removing Elements
• Searching and Counting
• Sorting and Reversing
• Copying and Slicing
List slices
• In Python, list slicing is a powerful technique that allows you to access
a subset of elements from a list. The general syntax for slicing is:

• list[start:stop:step]
Basic Slicing Examples
• Given the list:

numbers = [10, 20, 30, 40, 50, 60, 70]

• Slice from index 1 to 4 (excluding 4):

numbers[1:4] # Output: [20, 30, 40]


Slice from the beginning to index 3 (excluding 3):

numbers[:3]

# Output: [10, 20, 30]

• Slice from index 4 to the end:

numbers[4:] # Output: [50, 60, 70]

• Slice the entire list:


numbers[:] # Output: [10, 20, 30, 40, 50, 60, 70]
Using Negative Indices
• Negative indices allow you to slice from the end of the list:
• Last three elements:
numbers[-3:] # Output: [50, 60, 70]

All elements except the last one:


numbers[:-1] # Output: [10, 20, 30, 40, 50, 60]

Reversing the list:


numbers[::-1] # Output: [70, 60, 50, 40, 30, 20, 10]
Slicing with Steps
• The step parameter allows you to skip elements:

• Every second element:


numbers[::2] # Output: [10, 30, 50, 70]

• Every third element starting from index 1:


numbers[1::3] # Output: [20, 50]

•Elements from index 5 to 1 in reverse order, stepping by -2:


numbers[5:0:-2] # Output: [60, 40, 20]
List method
• ​Python provides a variety of built-in methods to manipulate lists,
allowing you to add, remove, search, and modify elements efficiently.

• Here's a comprehensive overview of commonly used list methods:​


Map
• ​In Python, the map() function is a built-in utility that allows you to
apply a specified function to each item of an iterable (like a list, tuple,
or set) and returns a map object (an iterator) containing the results.
• This approach is particularly useful for transforming data without the
need for explicit loops.
• Syntax
map(function, iterable, ...)

• The map() function applies the given function to each item of the
iterable(s) and returns a map object. To obtain a list of the results, you
can convert the map object using list()
Examples
• 1. Using map() with a Built-in Function

numbers = [1, 2, 3, 4]
squared = map(pow, numbers, numbers) # Equivalent to [1^1, 2^2,
3^3, 4^4]
print(list(squared))
# Output: [1, 4, 27, 256]
2. Using map() with a User-
defined Function
def square(n):
return n * n

numbers = [1, 2, 3, 4]
squared = map(square, numbers)
print(list(squared)) # Output: [1, 4, 9, 16]
3. Using map() with a Lambda
Function
numbers = [1, 2, 3, 4]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))

# Output: [1, 4, 9, 16]


4. Using map() with Multiple
Iterables
numbers1 = [2, 3, 4]
numbers2 = [5, 6, 7]
summed = map(lambda x, y: x + y, numbers1, numbers2)
print(list(summed))

# Output: [7, 9, 11]


When to Use map()

• When you need to apply a function to each item of an iterable


without writing an explicit loop.

• For operations that are stateless and can be applied independently to


each item.

• When working with large datasets where lazy evaluation can improve
performance.
Filter and reduce

• ​In Python, the filter() and reduce() functions are powerful tools for
processing iterables.
• Here's an overview of each:​
• filter() – Selecting Elements Based on a Condition
• Purpose: The filter() function constructs an iterator from elements of
an iterable for which a function returns True.
• filter(function, iterable)
Example: Filtering even
numbers from a list.
• numbers = [1, 2, 3, 4, 5, 6]
• even_numbers = filter(lambda x: x % 2 == 0, numbers)
• print(list(even_numbers))

• # Output: [2, 4, 6]
reduce() – Aggregating
Elements into a Single Value
• Purpose: The reduce() function applies a specified function
cumulatively to the items of an iterable, reducing the iterable to a
single accumulated value.​
• Note: In Python 3, reduce() is available in the functools module and
needs to be imported.

from functools import reduce


reduce(function, iterable)
Example: Calculating the sum of
a list of numbers.
from functools import reduce

numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print(sum_result) # Output: 15
Key Differences

Feature filter() reduce()


Select elements based on a Aggregate elements into a single
Purpose
condition value

Returns An iterator with selected elements A single accumulated value

Function Type Function that returns True or False Function that combines two values

Summing, multiplying, or reducing


Use Case Filtering data
data
Deleting elements
• 1. remove() – Delete by Value
• The remove() method deletes the first occurrence of a specified value
from the list.​
fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)

# Output: ['apple', 'cherry', 'banana']


2. pop() – Delete by Index and
Return the Value
• The pop() method removes the element at the specified index and
returns it. If no index is specified, it removes and returns the last item.​

numbers = [10, 20, 30, 40]


removed_item = numbers.pop(2)
print(removed_item) # Output: 30
print(numbers)
# Output: [10, 20, 40]
3. del – Delete by Index or Slice
• The del statement can remove elements by index or a range of indices (slice).​
colors = ['red', 'green', 'blue', 'yellow']
del colors[1]
print(colors) # Output: ['red', 'blue', 'yellow']

# Deleting a slice
del colors[1:3]
print(colors)
# Output: ['red']
4. clear() – Remove All Elements
• The clear() method removes all items from the list, resulting in an
empty list.

items = [1, 2, 3]
items.clear()
print(items)
# Output: []
5. List Comprehension – Remove
Elements Conditionally
• List comprehensions can create a new list excluding elements that
meet certain conditions.​

numbers = [1, 2, 3, 4, 5]
filtered = [num for num in numbers if num % 2 == 0]
print(filtered) # Output: [2, 4]
6. Removing Multiple Elements
• To remove multiple specific elements, you can use a loop or list
comprehension:

original = [10, 20, 30, 40, 50]


to_remove = [20, 40]
result = [item for item in original if item not in to_remove]
print(result)

# Output: [10, 30, 50]


List & Strings Key Differences

Feature Strings Lists


Mutability Immutable Mutable

Data Types Only characters (text) Any data type

Syntax Enclosed in quotes ("" or '') Enclosed in square brackets ([])

Modification Operations create new strings Can modify in place

Use Case Text manipulation Managing collections of items


Objects and values
• An object is an encapsulation of data (attributes) and behavior
(methods). In Python, everything is an object—including integers,
strings, functions, and even classes themselves.​Each object has
• Identity: A unique identifier for the object, which can be obtained
using the id() function. This identity remains constant during the
object's lifetime.​
• Type: The kind of object it is, determined by its class. You can retrieve
an object's type using the type() function.​
• Value: The data or content stored in the object.
• x = [1, 2, 3]
Values in Python
A value is the data contained within an object. It's the meaningful content that
the object represents.​
• For instance:
a = [1, 2, 3]
b = [1, 2, 3]

• Here, a and b are two distinct list objects (different identities) but have the
same value.​
• You can check:​
• Equality of values: a == b returns True because their contents are the same.​
• Identity: a is b returns False because they are different objects in memory.
Key Differences

Aspect Object Value


Definition An entity with identity, type, and value The data/content held by an object
Not unique; different objects can
Identity Unique; can be checked with id()
share it
Mutability Objects can be mutable or immutable Values can be shared across objects
Use is to check if two references point
Comparison to the same object
Use == to check if values are equal
aliasing
• In Python, aliasing occurs when multiple variables refer to the same
object in memory. This means that changes made through one
variable are reflected in the other, as they both point to the same
underlying data.
• Aliasing with Mutable Objects

• Aliasing is particularly significant with mutable objects like lists,


dictionaries, or custom objects.
Example:
a = [1, 2, 3]
b = a # b is now an alias for a
b[0] = 99
print(a)
# Output: [99, 2, 3]
Aliasing with Immutable Objects
• For immutable objects like integers, strings, or tuples, aliasing is less
of a concern since their values cannot be changed after creation.

x = "hello"
y=x
y = "world"
print(x)

# Output: "hello"
Checking for Aliasing
• You can check if two variables are aliases (i.e., refer to the same
object) using the is operator:

a = [1, 2, 3]
b=a
print(a is b)

# Output: True
Function Aliasing
• Aliasing can also apply to functions. Assigning a function to another
variable creates an alias:​

def greet():
print("Hello!")

say_hello = greet
say_hello()
# Output: Hello!
List arguments
• ​In Python, passing a list as an argument to a function allows the
function to access and manipulate the list's elements.

• Since lists are mutable, any changes made to the list within the
function will affect the original list outside the function.
Basic Example: Passing a List to
a Function
def print_list(a):
for item in a:
print(item)

fruits = ["apple", "banana", "cherry"]


print_list(fruits)

• apple
• banana
• cherry
Modifying the Original List
• Since lists are mutable, modifications within the function will affect
the original list.
def add_item(items, new_item):
items.append(new_item)

a = [1, 2, 3]
add_item(a, 4)
print(a)
[1, 2, 3, 4]
Using *args to Unpack a List
into Separate Arguments
• If you want to pass a list where each element is treated as a separate
argument, you can use the unpacking operator *

def greet(name, age):


print(f"Hello {name}, you are {age} years old.")

info = ["Alice", 30]


greet(*info)
• Hello Alice, you are 30 years old.
Dictionary

• In Python, a dictionary is a built-in data type that implements a


mapping—a collection of key-value pairs where each unique key
maps to a value.

• This allows for efficient data retrieval, insertion, and modification


using keys.​
Key Features of Python
Dictionaries
•Key-Value Pairs: Each item in a dictionary is a pair:
•Unique Keys: Keys must be unique and immutable (e.g., strings, numbers,
tuples).
•Mutable Values: Values can be of any data type and can be duplicated.
•Mutable and Dynamic: Dictionaries can be modified after creation—items can
be added, changed, or removed.
•Ordered: As of Python 3.7, dictionaries maintain insertion order.​
Creating and Using Dictionaries
• You can create a dictionary using curly braces {} or the dict()
constructor:

# Using curly braces


my_dict = {'name': 'Alice', 'age': 30}

# Using dict() constructor


my_dict = dict(name='Alice', age=30)
Accessing, adding, or updating
values is straightforward:
# Accessing a value
print(my_dict['name']) # Output: Alice

# Adding a new key-value pair


my_dict['city'] = 'New York'

# Updating an existing value


my_dict['age'] = 31
Mapping Keys to Values from
Lists
• You can create a dictionary by mapping keys to values from two separate lists using
dictionary comprehension or the zip() function:

keys = ['a', 'b', 'c']


values = [1, 2, 3]

# Using dictionary comprehension


my_dict = {keys[i]: values[i] for i in range(len(keys))}

# Using zip() function


my_dict = dict(zip(keys, values))

print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}


Applying Functions to Dictionary
Values
• To apply a function to each value in a dictionary, you can use
dictionary comprehension:

original_dict = {'a': 1, 'b': 2, 'c': 3}

# Applying a function to each value


squared_dict = {k: v**2 for k, v in original_dict.items()}

print(squared_dict) # Output: {'a': 1, 'b': 4, 'c': 9}


Dictionary as a collection of
counters.
• ​Yes, in Python, the collections.Counter class provides a specialized
dictionary subclass designed for counting hashable objects.

• It offers a convenient way to tally elements in an iterable or to count


the frequency of items in a mapping.​
What Is collections.Counter?
• Counter is part of Python’s collections module and functions as a
multiset—a collection where elements are stored as dictionary keys
and their counts as values.
• Unlike a regular dictionary, Counter returns a count of zero for missing
keys instead of raising a KeyError. ​
Creating a Counter
• You can initialize a Counter in several ways:

• 1. From an Iterable

from collections import Counter

data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']


counter = Counter(data)
print(counter)
2. From a Dictionary
counter = Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(counter)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})

• 3. Using Keyword Arguments

counter = Counter(apple=3, banana=2, orange=1)


print(counter)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
Practical Example: Word
Frequency
from collections import Counter

text = "the quick brown fox jumps over the lazy dog"
words = text.split()
word_counts = Counter(words)
print(word_counts)
# Output: Counter({'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1,
'over': 1, 'lazy': 1, 'dog': 1})
Looping and dictionaries
• ​Looping through dictionaries in Python is a fundamental skill, allowing
you to access and manipulate keys, values, or both.
• Here's a comprehensive guide on various methods to iterate over
dictionaries:​

my_dict = {'a': 1, 'b': 2, 'c': 3}


for key in my_dict.keys():
print(key) # OUTPUT: a b c
Looping Through Values
• To iterate over the values in a dictionary, use the .values() method:

for value in my_dict.values():


print(value)

# output;
1
2
3
Looping Through Key-Value
Pairs
• To access both keys and values simultaneously, use the .items()
method:

for key, value in my_dict.items():


print(f"{key}: {value}")
#output
a: 1
b: 2
c: 3
Reverse lookup
• In Python, performing a reverse lookup involves finding a key
associated with a given value in a dictionary.

• Since dictionaries are optimized for key-to-value lookups, reverse


lookups require additional steps. Here's how you can achieve this:​
1. Using a Generator Expression
• This method retrieves the first key that matches the specified value:

my_dict = {'a': 1, 'b': 2, 'c': 3}


value_to_find = 2

key = next((k for k, v in my_dict.items() if v == value_to_find), None)


print(key)
# Output: 'b'
2. Inverting the Dictionary
• If you need to perform multiple reverse lookups, creating an inverted
dictionary (values as keys and keys as values) can be more efficient:​

my_dict = {'a': 1, 'b': 2, 'c': 3}


inverted_dict = {v: k for k, v in my_dict.items()}

print(inverted_dict[2])
# Output: 'b'
3. Finding All Keys for a Given
Value
• To find all keys that map to a specific value:​

my_dict = {'a': 1, 'b': 2, 'c': 2, 'd': 3}


value_to_find = 2

keys = [k for k, v in my_dict.items() if v == value_to_find]


print(keys)
# Output: ['b', 'c']
Dictionaries and lists
• ​In Python, lists and dictionaries are fundamental data structures,
each serving distinct purposes and offering unique features.

Feature List Dictionary


Unordered (as of Python 3.7+,
Ordering Ordered
maintains insertion order)

Access Method By index By key

Duplicates Allows duplicate elements Keys must be unique

Mutability Mutable Mutable

Syntax [] {}
• List Example:
• pythonCopyEditfruits = ['apple', 'banana', 'cherry’]
• print(fruits[1])

• # Output: banana

• Dictionaries Example:
• person = {'name': 'Alice', 'age': 30}
• print(person['name'])
• # Output: Alice
Memos

• ​In Python, memoization is an optimization technique that stores the


results of expensive function calls and returns the cached result when
the same inputs occur again.

• This approach is particularly beneficial for recursive functions and


computations with overlapping subproblems, as it avoids redundant
calculations and enhances performance.​
Understanding Memoization
Memoization works by caching the results of function calls based on their
input arguments. When a memoized function is called, it first checks if
the result for the given inputs is already in the cache:​

If the result is cached: Return the cached result immediately.

1.If not: Compute the result, store it in the cache, and then return it.​

2.This technique is especially useful for functions that are deterministic


(i.e., always produce the same output for the same inputs) and have
expensive or repetitive computations.​
1. Using a Manual Cache with
Dictionaries
• You can implement memoization manually by using a dictionary to store computed
results:

factorial_memo = {}

def factorial(n):
if n < 2:
return 1
if n not in factorial_memo:
factorial_memo[n] = n * factorial(n - 1)
return factorial_memo[n]
2. Using functools.lru_cache
Decorator
• Python's functools module provides the lru_cache decorator, which simplifies
memoization:

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
Global variables

• ​In Python, global variables are variables defined outside of any


function, making them accessible throughout the entire program,
including within functions.

• Understanding how to use and manage global variables is essential


for effective Python programming.​
What Is a Global Variable?
• A global variable is declared outside of all functions and is accessible both inside

and outside of functions.

x = "awesome" # Global variable

def myfunc():
print("Python is " + x)

myfunc()
print("Outside function:", x)
#Output:Python is awesome
Outside function: awesome
Modifying Global Variables
Inside Functions
• By default, if you assign a value to a variable inside a function, Python treats it
as a local variable.
• To modify a global variable within a function, you must use the global
keyword.

x = 5 # Global variable

def myfunc():
global x
x = x + 1 # Modifies the global variable

myfunc()
Tuples: Tuples are immutable
• Tuples are immutable, meaning once created, their elements cannot
be changed, added, or removed.

# Example of a tuple
my_tuple = (1, 2, 3)

# Trying to change an element will cause an error


my_tuple[0] = 5 # ❌ This will raise a TypeError
Because of immutability:

• Tuples can be used as keys in dictionaries (if they contain only


immutable elements).

• Tuples are often used for fixed collections of items (like coordinates,
RGB colors, etc.).

• If you need a collection where you might need to modify the contents
later, use a list instead of a tuple.
1. Creating and Accessing Tuple
# Creating a tuple
fruits = ("apple", "banana", "cherry")

# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
2. Trying to Modify a Tuple
(Shows Error)
# Tuples are immutable
numbers = (1, 2, 3, 4)

# Trying to change an element


try:
numbers[0] = 10 # This will raise a TypeError
except TypeError as e:
print("Error:", e)
5. Tuple Packing and Unpacking
# Packing
person = ("John", 25, "Engineer")

# Unpacking
name, age, profession = person

print(name) # Output: John


print(age) # Output: 25
print(profession) # Output: Engineer
Tuple Assignment?
• In tuple assignment, you can assign values to multiple variables at once using a
tuple on both sides of the =

• Tuple assignment makes code shorter, cleaner, and easier to understand.

• 1. Basic Tuple Assignment:

# Assigning multiple variables at once


a, b, c = (1, 2, 3)

print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
2. Tuple Assignment Without
Parentheses
• You can even skip the parentheses:

• Python automatically treats the right-hand side as a tuple.

x, y = 10, 20
print(x) # Output: 10
print(y) # Output: 20
3. Swapping Two Variables
(Using Tuple Assignment)
# Swapping values without a temporary variable
m, n = 5, 10
m, n = n, m

print(m) # Output: 10
print(n) # Output: 5
4. Nested Tuple Assignment
# Nested tuples
(person, (city, country)) = ("Alice", ("Paris", "France"))

print(person) # Output: Alice


print(city) # Output: Paris
print(country) # Output: France
5. Using Tuple Assignment in
Loops
# List of tuples
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]

for num, word in pairs:


print(f"Number {num} is written as {word}")

Output:
Number 1 is written as one
Number 2 is written as two
Number 3 is written as three
Tuples as return values
• In Python, functions can return tuples, which is a convenient way to return
multiple values from a function.

• def min_max(numbers):
• minimum = min(numbers)
• maximum = max(numbers)
• return minimum, maximum # Returns a tuple

• result = min_max([3, 5, 1, 9, 2])


• print(result) # Output: (1, 9)
• print(result[0]) # Output: 1
• print(result[1]) # Output: 9
Unpacking the Tuple
low, high = min_max([3, 5, 1, 9, 2])
print("Minimum:", low) # Output: 1
print("Maximum:", high) # Output: 9
Another Example: Returning
Coordinates
def get_coordinates():
x = 10
y = 20
return x, y # Tuple: (10, 20)

# Unpack
x_pos, y_pos = get_coordinates()
print("X:", x_pos) # Output: 10
print("Y:", y_pos) # Output: 20
Why Use Tuples for Return
Values?
• Clean way to return multiple pieces of related data.
• Easy to unpack and Use.
• Helps avoid returning custom objects or multiple return statements.
Variable-length argument tuples
• In Python, you can define a function to accept any number of
positional arguments using *args.
• Here, args is a tuple that collects all the extra positional arguments
passed to the function.

• Syntax:
def function_name(*args):
# args is a tuple
Example 1: Sum of Any Number
of Arguments
def total_sum(*args):
return sum(args)

print(total_sum(1, 2, 3)) # Output: 6


print(total_sum(4, 5, 6, 7, 8)) # Output: 30
Example 2: Print Each Argument
def print_all(*args):
for item in args:
print(item)

print_all("apple", "banana", "cherry")

apple
banana
cherry
Lists and tuples
Feature List Tuple
Syntax my_list = [1, 2, 3] my_tuple = (1, 2, 3)
Mutable? Yes (can change) No (immutable)

Many methods
Methods available Fewer methods like .count(), .index()
like .append(), .remove()

Speed Slightly slower (more flexible) Faster (because of immutability)


Memory usage Uses more memory More memory-efficient

When values should remain


Use case When values may change
constant

Can be used as dict keys? No (mutable) Yes (if all elements are immutable)
When to Use What?
• Use lists when:
• You need to modify, add, or remove elements.
• Order matters and may change.
• Use tuples when:
• You want a fixed collection of items.
• You need to ensure data integrity.
• You want to use the values as dictionary keys or in sets.
Dictionaries and tuples.
Feature Dictionary (dict) Tuple (tuple)

Syntax {"key": "value"} (value1, value2, ...)

Mutable? Yes No

Key/Value Stores key-value pairs Stores ordered values

Indexed by Keys Integer positions (0, 1, 2...)

Use case Fast lookups by keys Fixed collections of items

Can be dictionary keys? No (if mutable) Yes (if tuple is immutable)


Example 1: Tuple as a Key in a
Dictionary
• Tuples are immutable, so they can be used as keys in a dictionary.

location_dict = {
(40.7128, -74.0060): "New York",
(34.0522, -118.2437): "Los Angeles"
}

print(location_dict[(40.7128, -74.0060)]) # Output: New York

You might also like