PLC142 (Python) Unit-2
PLC142 (Python) Unit-2
📌 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
✅ We can use negative indexing to access elements from the end ( -1 is the last element).
📌 Example:
fruits = ["apple", "banana", "cherry", "date"]
numbers = [1, 2, 3, 4, 5]
✔️ Output:
1
2
3
i=0
while i < len(numbers):
print(numbers[i])
i += 1
📌 Example:
items = ["pen", "notebook", "eraser"]
print(len(items)) # Output: 3
📌 Example:
fruits = ["apple", "banana", "cherry"]
🎯 Key Takeaways
✅ Lists store multiple values in an ordered sequence.
✅ Indexing starts from , and negative indexing accesses elements from the end.
0
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]
📌 Example:
numbers = [1, 2, 3]
repeated = numbers * 3
print(repeated)
✔️ Output:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
📌 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).
✔️ Output:
['apple', 'orange', 'cherry']
📌 Example:
numbers = [10, 20, 30, 40, 50]
✔️ Output:
[10, 20, 40, 50]
50
[10, 40]
list2[0] = 100
print(list1) # Affects both lists!
✔️ Output:
[100, 2, 3]
list2[0] = 100
print(list1) # Original list is unchanged
print(list2) # Modified copy
✔️ Output:
[1, 2, 3]
[100, 2, 3]
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.
📌 Example:
nested_list = [[1, 2, 3], ["apple", "banana", "cherry"], [True, False]]
print(nested_list)
✔️ Output:
[[1, 2, 3], ['apple', 'banana', 'cherry'], [True, False]]
✔️ Explanation:
matrix[0] returns the first inner list [10, 20, 30] .
✔️ Output:
123
456
789
✔️ Output:
[[1, 2, 3], [4, 50, 6]]
print(result)
✔️ Output:
[[6, 8], [10, 12]]
✔️ Output:
[1, 2, 3, 4, 5, 6, 7, 8]
✔️ Output:
['Python', 'is', 'fun']
data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits)
✔️ Output:
PLC142 (Python): Unit-2 7
['apple', 'banana', 'cherry']
✔️ Output:
Python is awesome
✔️ Output:
apple-banana-cherry
✔️ Output:
['h', 'e', 'l', 'l', 'o']
✔️ Output:
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
🔹 The spaces are removed, and the string is split into characters.
text = "Python"
reversed_text = text[::-1]
print(reversed_text)
✔️ Output:
nohtyP
text = "Python"
reversed_text = "".join(reversed(text))
print(reversed_text)
✔️ Output:
nohtyP
🔹 The reversed() function reverses the string, and join() combines it back.
✔️ 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:
✔️ Output:
[10, 20, 30, 40]
📌 Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
✔️ Output:
[1, 2, 3, 4, 5, 6]
📌 Example:
numbers = [10, 20, 30]
print(sum(numbers))
✔️ Output:
60
✔️ Output:
PLC142 (Python): Unit-2 10
3
📌 Example:
items = ["pen", "notebook", "eraser"]
print(len(items))
✔️ Output:
3
📌 Example:
colors = ["red", "blue", "green", "blue"]
print(colors.index("blue"))
✔️ Output:
1
📌 Example:
numbers = [10, 20, 30]
removed = numbers.pop()
print(numbers)
print("Removed:", removed)
✔️ Output:
[10, 20]
Removed: 30
✔️ Output:
✔️ Output:
[4, 3, 2, 1]
📌 Example:
values = [30, 10, 20, 40]
values.sort()
print(values)
✔️ Output:
[10, 20, 30, 40]
✔️ Output:
[40, 30, 20, 10]
numbers = [1, 2, 3]
new_numbers = double_values(numbers)
🔹 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)
def modify_double(lst):
for i in range(len(lst)):
numbers = [2, 3, 4]
🔹 The pure function ( pure_double() ) keeps the original list safe, while the modifier function ( modify_double() ) changes it.
📌 Example:
fruits = ("apple", "banana", "cherry")
print(fruits)
✔️ Output:
('apple', 'banana', 'cherry')
✔️ 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)
✔️ Output:
('Alice', 25, 'Engineer')
info = get_info()
print(info) # Output: ('Alice', 25, 'Engineer')
🔹 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'}
✔️ Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
✔️ Output:
{'name': 'Alice', 'age': 25, 'country': 'USA'}
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.
✔️ Output:
{'name': 'Emma', 'age': 23, 'grade': 'B'}
✔️ Output:
{'name': 'Emma', 'age': 22, 'grade': 'B', 'subject': 'Math'}
📌 Example:
print("name" in student) # Output: True
print("address" in student) # Output: False
📌 Example:
del student["grade"]
print(student)
✔️ Output:
{'name': 'Emma', 'age': 22}
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)])
✔️ Output:
{'name': 'Alice', 'grade': 'A'}
📌 Example:
person = {"name": "John", "age": 30, "city": "New York"}
print(person.keys())
✔️ Output:
dict_keys(['name', 'age', 'city'])
✔️ Output:
dict_values(['John', 30, 'New York'])
📌 Example:
print(person.items())
✔️ Output:
dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
📌 Example:
person.clear()
print(person)
✔️ Output:
{}
🔹 and point to the same memory, so changes in one reflect in the other.
list1 list2
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 .
list1 = [1, 2, 3]
list2 = list1[:] # Creates a new copy
dict2["y"] = 99
print(dict1) # Output: {'x': 10, 'y': 20} (original unchanged)
print(dict2) # Output: {'x': 10, 'y': 99} (copy modified)
📌 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)
-made by vijay