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

PLC142 (Python) Unit-2

The document covers various aspects of lists in Python, including their definition, accessing elements, using loops, and performing operations like concatenation and slicing. It also discusses nested lists, list membership, and converting between lists and strings. Key takeaways include the mutability of lists, methods for modifying them, and techniques for flattening nested lists.

Uploaded by

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

PLC142 (Python) Unit-2

The document covers various aspects of lists in Python, including their definition, accessing elements, using loops, and performing operations like concatenation and slicing. It also discusses nested lists, list membership, and converting between lists and strings. Key takeaways include the mutability of lists, methods for modifying them, and techniques for flattening nested lists.

Uploaded by

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

PLC142 (Python): Unit-2

🌟 Topic 1: Lists in Python 📋🔢


A list is a collection of values stored in an ordered sequence. Lists are one of the most important data structures in
Python! 🚀
🔹 1.1 What is a List? 🤔
✅ A list is an ordered collection of values.
✅ Each value in a list is called an element.
✅ Lists are mutable (we can change their elements).
✅ Lists are defined using square brackets . []

📌 Example:
numbers = [10, 20, 30, 40] # List of integers
words = ["apple", "banana", "cherry"] # List of strings
mixed = ["hello", 2.7, 5] # List with different data types
empty_list = [] # An empty list

🔹 1.2 Accessing List Elements 🔢


We use indexing to access elements in a list.
✅ Indexing starts from (first element = index ).
0 0

✅ We can use negative indexing to access elements from the end ( -1 is the last element).
📌 Example:
fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0]) # Output: apple


print(fruits[2]) # Output: cherry
print(fruits[-1]) # Output: date (last element)
print(fruits[-2]) # Output: cherry (second last element)

❌ Accessing an invalid index results in an error!


print(fruits[10]) # IndexError: list index out of range

🔹 1.3 Using Loops with Lists 🔄


We can use loops to go through all elements in a list.
📌 Using for Loop:

numbers = [1, 2, 3, 4, 5]

for num in numbers:


print(num) # Prints each number in the list

✔️ Output:
1
2
3

PLC142 (Python): Unit-2 1


4
5

📌 Using while Loop:

i=0
while i < len(numbers):
print(numbers[i])
i += 1

✔️ Output: (Same as above!)


🔹 1.4 Finding the Length of a List 📏
✅ Use to find the number of elements in a list.
len()

📌 Example:
items = ["pen", "notebook", "eraser"]
print(len(items)) # Output: 3

🔹 1.5 Nested Lists (Lists Within Lists) 🏗️


✅ A nested list is a list inside another list.
✅ We use double indexing to access elements inside nested lists.
📌 Example:
nested = [[1, 2, 3], ["a", "b", "c"], [True, False]]

print(nested[0]) # Output: [1, 2, 3]


print(nested[1][2]) # Output: c (second list, third element)

🔹 1.6 Checking List Membership ( in Operator) ✅❌


✅ We use to check if a value exists in a list.
in

📌 Example:
fruits = ["apple", "banana", "cherry"]

print("apple" in fruits) # Output: True


print("mango" in fruits) # Output: False

🎯 Key Takeaways
✅ Lists store multiple values in an ordered sequence.
✅ Indexing starts from , and negative indexing accesses elements from the end.
0

✅ Loops help iterate through list elements.


✅ returns the number of elements in a list.
len()

✅ Nested lists store lists inside lists.


✅ The operator checks if an element exists in a list.
in

🌟 Topic 2: List Operations & Slices 🔢✨


PLC142 (Python): Unit-2 2
🔹 2.1 List Concatenation ( + Operator) ➕
The + operator combines two lists into a single list.

It does not modify the original lists but creates a new list.

📌 Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)

✔️ Output:
[1, 2, 3, 4, 5, 6]

🔹 Original lists remain unchanged!


🔹 2.2 List Repetition ( Operator) 🔄
The operator repeats a list multiple times.

This creates a new list without modifying the original.

📌 Example:
numbers = [1, 2, 3]
repeated = numbers * 3
print(repeated)

✔️ Output:
[1, 2, 3, 1, 2, 3, 1, 2, 3]

🔹 The list is duplicated 3 times.


🔹 2.3 List Slicing 🏗️
Slicing extracts a portion of a list using [start:stop:step] .

The start index is included, but the stop index is excluded.

📌 Example:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # Elements from index 1 to 3
print(numbers[:3]) # First 3 elements
print(numbers[2:]) # Elements from index 2 to the end
print(numbers[::2]) # Every second element

✔️ Output:
[20, 30, 40]
[10, 20, 30]
[30, 40, 50, 60]
[10, 30, 50]

🔹 The step controls how elements are selected ( ::2 picks every second item).

🔹 2.4 Lists are Mutable (Modifying Lists) 🔄


Lists can be changed by assigning new values to elements.

PLC142 (Python): Unit-2 3


📌 Example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)

✔️ Output:
['apple', 'orange', 'cherry']

🔹 The second element ( "banana" ) is replaced with "orange" .

🔹 2.5 Deleting List Elements 🗑️


✅ Using keyword: Removes an element at a specific index.
del

✅ Using method: Removes and returns an element.


pop()

✅ Using method: Removes a specific value.


remove()

📌 Example:
numbers = [10, 20, 30, 40, 50]

del numbers[2] # Removes element at index 2


print(numbers)

removed = numbers.pop() # Removes last element


print(removed)

numbers.remove(20) # Removes first occurrence of 20


print(numbers)

✔️ Output:
[10, 20, 40, 50]
50
[10, 40]

🔹 del and pop() use an index, while remove() searches by value.

🔹 2.6 Aliasing vs. Cloning Lists 🎭


Aliasing: Two variables refer to the same list.

Cloning: A new copy of the list is created.

📌 Aliasing Example (Same List in Memory):


list1 = [1, 2, 3]
list2 = list1 # Both point to the same list

list2[0] = 100
print(list1) # Affects both lists!

✔️ Output:
[100, 2, 3]

🔹 Both and refer to the same list!


list1 list2

📌 Cloning Example (Independent Lists):

PLC142 (Python): Unit-2 4


list1 = [1, 2, 3]
list2 = list1[:] # Creates a copy

list2[0] = 100
print(list1) # Original list is unchanged
print(list2) # Modified copy

✔️ Output:
[1, 2, 3]
[100, 2, 3]

🔹 Cloning ensures original data remains safe.


🔹 2.7 Passing Lists as Function Parameters 🎯
✅ Lists can be passed as function arguments and modified inside functions.
📌 Example:
def double_values(lst):
for i in range(len(lst)):
lst[i] *= 2

numbers = [1, 2, 3]
double_values(numbers)
print(numbers)

✔️ Output:
[2, 4, 6]

🔹 Lists are passed by reference, meaning modifications affect the original list.
🌟 Topic 3: Nested Lists & Matrices 🔢📦
🔹 3.1 What are Nested Lists? 🏗️
A nested list is a list inside another list.

It allows storing structured data like tables, matrices, or hierarchical information.

📌 Example:
nested_list = [[1, 2, 3], ["apple", "banana", "cherry"], [True, False]]
print(nested_list)

✔️ Output:
[[1, 2, 3], ['apple', 'banana', 'cherry'], [True, False]]

🔹 Each inner list acts as a separate group of values.


🔹 3.2 Accessing Elements in a Nested List 🔍
✅ Use double indexing to retrieve elements from nested lists.
The first index refers to the inner list.

The second index refers to the element inside that list.

PLC142 (Python): Unit-2 5


📌 Example:
matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]

print(matrix[0]) # Output: [10, 20, 30]


print(matrix[1][2]) # Output: 60
print(matrix[2][0]) # Output: 70

✔️ Explanation:
matrix[0] returns the first inner list [10, 20, 30] .

matrix[1][2] accesses the third element ( 60 ) of the second inner list.

matrix[2][0] gets the first element ( 70 ) of the third inner list.

🔹 3.3 Using Loops with Nested Lists 🔄


✅ We can use nested loops to access all elements in a nested list.
📌 Example: Printing Elements in a Matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:


for element in row:
print(element, end=" ")
print() # New line after each row

✔️ Output:
123
456
789

🔹 Outer loop iterates over each row.


🔹 Inner loop prints elements within the row.
🔹 3.4 Modifying Elements in a Nested List ✏️
✅ Since lists are mutable, we can modify values inside nested lists.
📌 Example:
matrix = [[1, 2, 3], [4, 5, 6]]

matrix[1][1] = 50 # Changing the middle value


print(matrix)

✔️ Output:
[[1, 2, 3], [4, 50, 6]]

🔹 The second row, second column value is updated to 50 .

🔹 3.5 Working with Matrices Using Nested Lists 🔢


✅ A matrix is a grid of numbers (rows & columns).
✅ Nested lists store matrices in Python.
📌 Example: Matrix Addition

PLC142 (Python): Unit-2 6


A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]

result = [[0, 0], [0, 0]] # Create an empty matrix

for i in range(len(A)): # Loop through rows


for j in range(len(A[0])): # Loop through columns
result[i][j] = A[i][j] + B[i][j]

print(result)

✔️ Output:
[[6, 8], [10, 12]]

🔹 Each element in A and B is added together to form the result.

🔹 3.6 Converting a Nested List to a Single List (Flattening) 📏


✅ Flattening means converting a nested list into a single list.
📌 Example:
nested = [[1, 2, 3], [4, 5], [6, 7, 8]]

flat_list = [num for sublist in nested for num in sublist]


print(flat_list)

✔️ Output:
[1, 2, 3, 4, 5, 6, 7, 8]

🔹 This extracts all elements into a single list.


🌟 Topic 4: Lists & Strings 🔡📋
🔹 4.1 Converting Strings to Lists ( split() ) 🔀
✅ The method converts a string into a list by splitting it at spaces or a specific character.
split()

📌 Example: Splitting a Sentence into Words


sentence = "Python is fun"
words = sentence.split()
print(words)

✔️ Output:
['Python', 'is', 'fun']

🔹 The string is split into words based on spaces.


📌 Example: Splitting Using a Comma ( ) ","

data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits)

✔️ Output:
PLC142 (Python): Unit-2 7
['apple', 'banana', 'cherry']

🔹 The string is split at commas into a list of words.


🔹 4.2 Converting Lists to Strings ( join() ) 🔄
✅ The method converts a list back into a string.
join()

✅ We specify a separator (space, comma, etc.) between elements.


📌 Example: Joining a List into a Sentence
words = ['Python', 'is', 'awesome']
sentence = " ".join(words)
print(sentence)

✔️ Output:
Python is awesome

🔹 The list is combined into a single string with spaces.


📌 Example: Joining Using a Hyphen ( ) "-"

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


text = "-".join(fruits)
print(text)

✔️ Output:
apple-banana-cherry

🔹 The list elements are joined with hyphens instead of spaces.


🔹 4.3 Converting Characters of a String into a List
✅ A string is a sequence of characters, so we can convert it into a list of letters.
📌 Example:
word = "hello"
char_list = list(word)
print(char_list)

✔️ Output:
['h', 'e', 'l', 'l', 'o']

🔹 Each letter becomes a separate element in the list.


📌 Example: Removing Spaces Before Converting to a List
text = "Hello World"
char_list = list(text.replace(" ", "")) # Remove spaces first
print(char_list)

✔️ Output:
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']

🔹 The spaces are removed, and the string is split into characters.

PLC142 (Python): Unit-2 8


🔹 4.4 Reversing a String Using Lists
✅ We can reverse a string using list slicing or the reversed() function.
📌 Example: Using Slicing ( ) [::-1]

text = "Python"
reversed_text = text[::-1]
print(reversed_text)

✔️ Output:
nohtyP

🔹 The string is reversed using slicing.


📌 Example: Using & reversed() join()

text = "Python"
reversed_text = "".join(reversed(text))
print(reversed_text)

✔️ Output:
nohtyP

🔹 The reversed() function reverses the string, and join() combines it back.

🔹 4.5 Checking if a String is a Palindrome 🪞


✅ A palindrome is a word that reads the same forward and backward.
📌 Example: Palindrome Check Using Lists
def is_palindrome(word):
return word == word[::-1] # Check if reversed word is same

print(is_palindrome("madam")) # Output: True


print(is_palindrome("hello")) # Output: False

✔️ Output:
True
False

🔹 The function checks if the word and its reverse are the same.
🌟 Topic 5: List Methods 📋🔧
🔹 5.1 Adding Elements to a List ( append() )
✅ The append() method adds an element to the end of a list.

📌 Example:
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)

✔️ Output:

PLC142 (Python): Unit-2 9


['apple', 'banana', 'cherry']

🔹 Adds "cherry" to the end of the list.

🔹 5.2 Inserting Elements at a Specific Position ( insert() )


✅ The insert() method inserts an element at a specific index.
📌 Example:
numbers = [10, 20, 40]
numbers.insert(2, 30) # Insert 30 at index 2
print(numbers)

✔️ Output:
[10, 20, 30, 40]

🔹 "30" is inserted at index 2, shifting other elements.

🔹 5.3 Extending a List ( extend() )


✅ The extend() method adds multiple elements from another list.

📌 Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)

✔️ Output:
[1, 2, 3, 4, 5, 6]

🔹 Merges list2 into list1 .

🔹 5.4 Summing Elements in a List ( sum() )


✅ The function returns the total sum of elements in a list.
sum()

📌 Example:
numbers = [10, 20, 30]
print(sum(numbers))

✔️ Output:
60

🔹 Works only with numerical lists.


🔹 5.5 Counting Occurrences of an Element ( count() )
✅ The count() method returns the number of times a value appears in a list.
📌 Example:
letters = ["a", "b", "a", "c", "a"]
print(letters.count("a"))

✔️ Output:
PLC142 (Python): Unit-2 10
3

🔹 "a" appears 3 times in the list.

🔹 5.6 Finding the Length of a List ( len() )


✅ The function returns the number of elements in a list.
len()

📌 Example:
items = ["pen", "notebook", "eraser"]
print(len(items))

✔️ Output:
3

🔹 Counts the total number of elements in the list.


🔹 5.7 Finding the Index of an Element ( index() )
✅ The method returns the first occurrence of a value.
index()

📌 Example:
colors = ["red", "blue", "green", "blue"]
print(colors.index("blue"))

✔️ Output:
1

🔹 "blue" first appears at index 1 .

🔹 5.8 Removing Elements from a List ( pop() )


✅ The method removes an element at a given index (default is the last element).
pop()

📌 Example:
numbers = [10, 20, 30]
removed = numbers.pop()
print(numbers)
print("Removed:", removed)

✔️ Output:
[10, 20]
Removed: 30

🔹 Removes the last element ( ) and returns it.


30

📌 Example: Removing a Specific Index


numbers = [10, 20, 30, 40]
numbers.pop(1) # Removes element at index 1
print(numbers)

✔️ Output:

PLC142 (Python): Unit-2 11


[10, 30, 40]

🔹 Removes the element at index 1 ( 20 ).

🔹 5.9 Reversing a List ( reverse() )


✅ The reverse() method reverses the order of elements.
📌 Example:
nums = [1, 2, 3, 4]
nums.reverse()
print(nums)

✔️ Output:
[4, 3, 2, 1]

🔹 The list is flipped in reverse order.


🔹 5.10 Sorting a List ( sort() )
✅ The method sorts elements in ascending order (default).
sort()

✅ Use for descending order.


reverse=True

📌 Example:
values = [30, 10, 20, 40]
values.sort()
print(values)

✔️ Output:
[10, 20, 30, 40]

🔹 The list is sorted in increasing order.


📌 Sorting in Descending Order:
values.sort(reverse=True)
print(values)

✔️ Output:
[40, 30, 20, 10]

🔹 The list is sorted in decreasing order.


🌟 Topic 6: Pure Functions & Modifiers 🔍🔄
🔹 6.1 What are Pure Functions? 💡
✅ A pure function does not modify the input data but returns a new result.
✅ It only depends on its arguments and has no side effects (does not change external variables).
📌 Example:
def add_numbers(a, b):
return a + b # Returns a new value without modifying inputs

PLC142 (Python): Unit-2 12


x=5
y = 10
result = add_numbers(x, y)
print(result) # Output: 15

🔹 add_numbers() is pure because it does not modify x or y .

🔹 6.2 Characteristics of Pure Functions


✔️ Does not modify external variables
✔️ Always returns a result
✔️ For the same input, always gives the same output
📌 Example: Pure Function That Creates a New List
def double_values(lst):
return [x * 2 for x in lst] # Creates a new list without modifying original

numbers = [1, 2, 3]
new_numbers = double_values(numbers)

print(numbers) # Output: [1, 2, 3] (original unchanged)


print(new_numbers) # Output: [2, 4, 6] (new list created)

🔹 The function does not change the original list but returns a new list.
🔹 6.3 What are Modifiers? 🔄
✅ Modifiers (Impure Functions) change the original data instead of creating a new copy.
✅ They modify lists, dictionaries, or global variables inside the function.
📌 Example:
def double_in_place(lst):
for i in range(len(lst)):
lst[i] *= 2 # Modifies the original list

numbers = [1, 2, 3]
double_in_place(numbers)

print(numbers) # Output: [2, 4, 6] (original list modified)

🔹 double_in_place() changes the actual list instead of creating a new one.

🔹 6.4 Difference Between Pure Functions & Modifiers 🆚


Feature Pure Function Modifier

Modifies Original Data? ❌ No ✅ Yes


Returns a New Copy? ✅ Yes ❌ No
Side Effects? ❌ None ✅ Can change external variables
📌 Example: Pure vs. Modifier Comparison
def pure_double(lst):
return [x * 2 for x in lst] # Returns new list

def modify_double(lst):
for i in range(len(lst)):

PLC142 (Python): Unit-2 13


lst[i] *= 2 # Changes the original list

numbers = [2, 3, 4]

new_list = pure_double(numbers) # New list created


modify_double(numbers) # Original list modified

print(new_list) # Output: [4, 6, 8]


print(numbers) # Output: [4, 6, 8] (modified)

🔹 The pure function ( pure_double() ) keeps the original list safe, while the modifier function ( modify_double() ) changes it.

🌟 Topic 7: Tuples in Python 🎭🔢


🔹 7.1 Introduction to Tuples
✅ A tuple is an ordered collection of elements, similar to a list.
✅ Tuples are immutable (cannot be changed after creation).
✅ Defined using parentheses ( ), not square brackets ( ).
() []

📌 Example:
fruits = ("apple", "banana", "cherry")
print(fruits)

✔️ Output:
('apple', 'banana', 'cherry')

🔹 Tuples preserve the order of elements.


🔹 7.2 Creating Tuples
📌 Example:
numbers = (10, 20, 30)
print(numbers)

✔️ Output:
(10, 20, 30)

🔹 Tuples can store different data types like strings, numbers, or even lists.
📌 Example: Tuple with Mixed Data Types
mixed = ("hello", 25, 3.14, True)
print(mixed)

✔️ Output:
('hello', 25, 3.14, True)

🔹 Elements can be of different types but cannot be modified.


🔹 7.3 Tuple with a Single Element
✅ A single-element tuple must have a comma ( , ) after the value.

PLC142 (Python): Unit-2 14


📌 Example:
single = ("hello",) # Comma is required!
not_a_tuple = ("hello") # This is just a string

✔️ Checking Data Types:


print(type(single)) # Output: <class 'tuple'>
print(type(not_a_tuple)) # Output: <class 'str'>

🔹 The comma differentiates a tuple from a string.


🔹 7.4 Tuples are Immutable 🚫✏️
✅ Tuples cannot be modified after creation.
❌ Trying to change a tuple gives an error!
📌 Example:
numbers = (1, 2, 3)
numbers[0] = 10 # ❌ ERROR!
✔️ Output:
TypeError: 'tuple' object does not support item assignment

🔹 Once created, tuple elements cannot be changed, added, or removed.


🔹 7.5 Tuple Packing & Unpacking 📦🎁
✅ Packing → Assigning multiple values into a tuple.
✅ Unpacking → Extracting values from a tuple into variables.
📌 Example: Packing a Tuple
person = ("Alice", 25, "Engineer")
print(person)

✔️ Output:
('Alice', 25, 'Engineer')

📌 Example: Unpacking a Tuple


name, age, job = person
print(name) # Output: Alice
print(age) # Output: 25
print(job) # Output: Engineer

🔹 Each tuple element is assigned to a separate variable.


🔹 7.6 Tuple Assignment
✅ Tuples allow multiple variable assignments in one line.
📌 Example:
a, b, c = 10, 20, 30
print(a, b, c)

PLC142 (Python): Unit-2 15


✔️ Output:
10 20 30

🔹 This is called tuple unpacking and simplifies variable assignments.


🔹 7.7 Tuples as Function Return Values
✅ Functions can return multiple values as a tuple.
📌 Example:
def get_info():
return "Alice", 25, "Engineer"

info = get_info()
print(info) # Output: ('Alice', 25, 'Engineer')

🔹 The function returns multiple values as a tuple.


📌 Example: Unpacking Returned Tuple
name, age, job = get_info()
print(name) # Output: Alice

🔹 This allows multiple values to be returned and assigned easily.


🔹 7.8 Tuples Inside Tuples (Composability of Data Structures)
✅ Tuples can contain other tuples, creating a nested structure.
📌 Example:
nested_tuple = ((1, 2, 3), ("a", "b", "c"))
print(nested_tuple)
print(nested_tuple[1][2]) # Output: c

🔹 The first index accesses the inner tuple, and the second index accesses the element inside it.
🌟 Topic 8: Dictionaries in Python 📖🔑
🔹 8.1 Introduction to Dictionaries
✅ A dictionary is a collection of key-value pairs.
✅ Unlike lists, dictionaries store data in an unordered format.
✅ Dictionaries use curly braces to store elements. {}

📌 Example:
student = {"name": "Alice", "age": 25, "grade": "A"}
print(student)

✔️ Output:
{'name': 'Alice', 'age': 25, 'grade': 'A'}

🔹 Keys ( "name" , "age" , "grade" ) are unique identifiers.


🔹 Values ( "Alice" , 25 , "A" ) store the actual data.

🔹 8.2 Creating Dictionaries


PLC142 (Python): Unit-2 16
✅ Dictionaries can be created in multiple ways.
📌 Example: Using {}

person = {"name": "John", "age": 30, "city": "New York"}


print(person)

✔️ Output:
{'name': 'John', 'age': 30, 'city': 'New York'}

📌 Example: Using dict() Function

data = dict(name="Alice", age=25, country="USA")


print(data)

✔️ Output:
{'name': 'Alice', 'age': 25, 'country': 'USA'}

🔹 The dict() function creates a dictionary without curly braces.

🔹 8.3 Accessing Dictionary Values


✅ Use keys to retrieve values.
✅ If a key does not exist, Python raises a KeyError.
📌 Example:
student = {"name": "Emma", "age": 22, "grade": "B"}
print(student["name"]) # Output: Emma
print(student["age"]) # Output: 22

📌 Avoiding KeyError Using get() Method

print(student.get("grade")) # Output: B
print(student.get("address", "Not Found")) # Output: Not Found

🔹 get() prevents errors and returns "Not Found" if the key is missing.

🔹 8.4 Updating Dictionary Values


✅ Dictionary values can be modified by assigning new values.
📌 Example:
student["age"] = 23
print(student)

✔️ Output:
{'name': 'Emma', 'age': 23, 'grade': 'B'}

🔹 The "age" value is updated to 23.

🔹 8.5 Adding New Key-Value Pairs


✅ Assign a new key to add data.
📌 Example:

PLC142 (Python): Unit-2 17


student["subject"] = "Math"
print(student)

✔️ Output:
{'name': 'Emma', 'age': 22, 'grade': 'B', 'subject': 'Math'}

🔹 "subject" is added dynamically to the dictionary.

🔹 8.6 Checking if a Key Exists ( in Operator)


✅ The operator checks if a key exists.
in

📌 Example:
print("name" in student) # Output: True
print("address" in student) # Output: False

🔹 Returns True if the key exists and False if it doesn't.

🔹 8.7 Removing Key-Value Pairs ( del )


✅ Use to remove a key-value pair.
del

📌 Example:
del student["grade"]
print(student)

✔️ Output:
{'name': 'Emma', 'age': 22}

🔹 The "grade" key is removed.

🔹 8.8 Dictionary Methods ( keys() , items() , etc.)

Method Description
keys() Returns a list of all keys in the dictionary
values() Returns a list of all values
items() Returns key-value pairs as tuples
clear() Removes all items from the dictionary

📌 Example:
print(student.keys()) # Output: dict_keys(['name', 'age'])
print(student.values()) # Output: dict_values(['Emma', 22])
print(student.items()) # Output: dict_items([('name', 'Emma'), ('age', 22)])

🌟 Topic 9: Dictionary Operations & Methods 📖🔧


🔹 9.1 Deleting Key-Value Pairs ( del )
✅ Use the del keyword to remove a specific key-value pair.
📌 Example:
student = {"name": "Alice", "age": 25, "grade": "A"}
del student["age"]

PLC142 (Python): Unit-2 18


print(student)

✔️ Output:
{'name': 'Alice', 'grade': 'A'}

🔹 The "age" key is deleted from the dictionary.

🔹 9.2 Getting All Keys ( keys() )


✅ The method returns a list of all dictionary keys.
keys()

📌 Example:
person = {"name": "John", "age": 30, "city": "New York"}
print(person.keys())

✔️ Output:
dict_keys(['name', 'age', 'city'])

🔹 The method returns all keys in the dictionary.


🔹 9.3 Getting All Values ( values() )
✅ The values() method returns a list of all values.
📌 Example:
print(person.values())

✔️ Output:
dict_values(['John', 30, 'New York'])

🔹 The method returns all values from the dictionary.


🔹 9.4 Getting All Key-Value Pairs ( items() )
✅ The method returns key-value pairs as tuples.
items()

📌 Example:
print(person.items())

✔️ Output:
dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

🔹 Each key-value pair is returned as a tuple.


🔹 9.5 Checking If a Key Exists ( in Operator)
✅ Use the in operator to check if a key exists in a dictionary.
📌 Example:
print("age" in person) # Output: True
print("salary" in person) # Output: False

🔹 Returns True if the key exists and False if it doesn't.

PLC142 (Python): Unit-2 19


🔹 9.6 Removing All Items from a Dictionary ( clear() )
✅ The method removes all elements from a dictionary.
clear()

📌 Example:
person.clear()
print(person)

✔️ Output:
{}

🔹 The dictionary is now empty.


🌟 Topic 10: Aliasing & Copying Data Structures 🔄📋
🔹 10.1 What is Aliasing in Lists & Dictionaries?
✅ Aliasing means assigning one variable to another, making both refer to the same memory location.
✅ Changes in one variable affect the other.
📌 Example: Aliasing a List
list1 = [10, 20, 30]
list2 = list1 # Aliasing: Both refer to the same list

list2[1] = 99 # Modify list2


print(list1) # Output: [10, 99, 30] (list1 also changes!)

🔹 and point to the same memory, so changes in one reflect in the other.
list1 list2

📌 Example: Aliasing a Dictionary


dict1 = {"a": 1, "b": 2}
dict2 = dict1 # Aliasing

dict2["b"] = 99
print(dict1) # Output: {'a': 1, 'b': 99} (dict1 also changes!)

🔹 Both variables refer to the same dictionary, so modifying dict2 affects dict1 .

🔹 10.2 What is Copying? (Creating a New Independent Copy)


✅ Copying creates a new object, so modifications do not affect the original data.
✅ Use slicing ( ), , or to make a copy.
[:] copy() dict()

📌 Example: Copying a List Using Slicing ( ) [:]

list1 = [1, 2, 3]
list2 = list1[:] # Creates a new copy

list2[0] = 99 # Modify copy


print(list1) # Output: [1, 2, 3] (original unchanged)
print(list2) # Output: [99, 2, 3] (copy modified)

🔹 The original list remains unchanged because list2 is a new list.


📌 Example: Copying a Dictionary Using copy()

PLC142 (Python): Unit-2 20


dict1 = {"x": 10, "y": 20}
dict2 = dict1.copy() # Creates a new dictionary copy

dict2["y"] = 99
print(dict1) # Output: {'x': 10, 'y': 20} (original unchanged)
print(dict2) # Output: {'x': 10, 'y': 99} (copy modified)

🔹 The copy does not affect the original dictionary.


🔹 10.3 Difference Between Aliasing & Copying
Feature Aliasing Copying

Memory Location Same for both variables Different (new object)

Changes in One Affects Other? ✅ Yes ❌ No


How to Create? list2 = list1 list2 = list1[:] or list1.copy()

📌 Example:
a = [1, 2, 3]
b = a # Aliasing
c = a[:] # Copying

b[0] = 99
print(a) # Output: [99, 2, 3] (Aliasing affects a)
print(c) # Output: [1, 2, 3] (Copy remains unchanged)

🔹 b shares memory with a , but c is a separate copy.

-made by vijay

PLC142 (Python): Unit-2 21

You might also like