Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Solution

The document provides an overview of various Python data structures including lists, tuples, sets, and dictionaries, along with their operations and methods. It covers list slicing, element manipulation functions (append, insert, extend), deletion methods (del, remove, pop, clear), and tuple immutability. Additionally, it discusses set operations (union, intersection, difference, symmetric difference) and dictionary management (declaration, access, update, and removal of key-value pairs).

Uploaded by

prameshingle3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Solution

The document provides an overview of various Python data structures including lists, tuples, sets, and dictionaries, along with their operations and methods. It covers list slicing, element manipulation functions (append, insert, extend), deletion methods (del, remove, pop, clear), and tuple immutability. Additionally, it discusses set operations (union, intersection, difference, symmetric difference) and dictionary management (declaration, access, update, and removal of key-value pairs).

Uploaded by

prameshingle3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Python Assignment

1. Write a short note on slicing a list.


List Slicing in Python
List slicing in Python allows extracting a specific portion of a list
using the syntax:
list[start:stop:step]
• start: Index where slicing begins (default is 0).
• stop: Index where slicing ends (excluded).
• step: Interval between elements (default is 1).
Example:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[::2]) # Output: [10, 30, 50]
print(numbers[::-1]) # Output: [60, 50, 40, 30, 20, 10] (Reversed
list)
Slicing helps in efficient data manipulation, subsetting, and
reversing lists.

P a g e 1 | 21
Python Assignment

2. Explain the following functions with respect to a list:


a) `append()` function
b) `insert()` function
c) `extend()` function
List Functions in Python
Python provides several built-in functions to manipulate lists
efficiently. Below are explanations of the append(), insert(), and
extend() functions:
a) append() Function
The append() function adds a single element to the end of the list.
It modifies the list in place.
Syntax:
list.append(element)
Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
b) insert() Function
The insert() function adds an element at a specific index, shifting
the existing elements to the right.
Syntax:
list.insert(index, element)
Example:
numbers = [1, 2, 4]

P a g e 2 | 21
Python Assignment

numbers.insert(2, 3)
print(numbers) # Output: [1, 2, 3, 4]
c) extend() Function
The extend() function adds multiple elements (iterable) to the
end of the list. Unlike append(), which adds a single element,
extend() merges the given iterable.
Syntax:
list.extend(iterable)
Example:
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
These functions enhance list manipulation, making data handling
more efficient in Python.

P a g e 3 | 21
Python Assignment

3. Can we delete list elements? Justify your answer.


Deleting List Elements in Python
Yes, it is possible to delete elements from a list in Python using
various methods. Lists are mutable, meaning their elements can
be modified, added, or removed dynamically.
Methods to Delete Elements:
Using del Statement – Removes an element at a specific index
or deletes the entire list.
numbers = [10, 20, 30, 40]
del numbers[1] # Deletes element at index 1
print(numbers) # Output: [10, 30, 40]

Using remove() Method – Deletes the first occurrence of a


specified value.
numbers = [10, 20, 30, 20]
numbers.remove(20) # Removes first occurrence of 20
print(numbers) # Output: [10, 30, 20]

Using pop() Method – Removes and returns an element at a


given index (default is the last element).
numbers = [10, 20, 30]
removed = numbers.pop(1) # Removes element at index 1
print(numbers) # Output: [10, 30]
print(removed) # Output: 20

P a g e 4 | 21
Python Assignment

Using Slicing – Removes multiple elements efficiently.


numbers = [10, 20, 30, 40, 50]
numbers[1:3] = [] # Deletes elements at indices 1 and 2
print(numbers) # Output: [10, 40, 50]

Using clear() Method – Removes all elements from the list.


numbers = [10, 20, 30]
numbers.clear()
print(numbers) # Output: []
Thus, list elements can be deleted using different approaches,
depending on whether a specific element, index, or the entire list
needs to be removed.

P a g e 5 | 21
Python Assignment

4. Explain the use of keywords `del`, `remove()` function,


`pop()` function, and `clear()` function with respect to a list.
List Modification Methods in Python
Python provides multiple ways to modify lists by deleting
elements. Below are the key methods:
1. del Keyword
The del keyword removes elements from a list based on their
index or deletes the entire list.
Usage:
numbers = [10, 20, 30, 40]
del numbers[1] # Removes element at index 1
print(numbers) # Output: [10, 30, 40]

del numbers # Deletes the entire list


# print(numbers) # Raises NameError: 'numbers' is not defined
2. remove() Function
The remove() function deletes the first occurrence of a specified
value. If the value is not found, it raises an error.
Usage:
numbers = [10, 20, 30, 20]
numbers.remove(20) # Removes first occurrence of 20
print(numbers) # Output: [10, 30, 20]
3. pop() Function

P a g e 6 | 21
Python Assignment

The pop() function removes and returns an element at a specified


index. If no index is given, it removes the last element.
Usage:
numbers = [10, 20, 30]
removed = numbers.pop(1) # Removes element at index 1
print(numbers) # Output: [10, 30]
print(removed) # Output: 20
4. clear() Function
The clear() function removes all elements from a list, leaving it
empty.
Usage:
numbers = [10, 20, 30]
numbers.clear()
print(numbers) # Output: []
Each method serves different use cases, from deleting specific
elements to emptying or removing entire lists.

P a g e 7 | 21
Python Assignment

5. How do you declare a tuple? Can it be changed or updated?


Can tuple elements be changed? Justify your answer.
Tuples in Python
Declaring a Tuple
A tuple in Python is declared using parentheses () and can contain
elements of different data types.
Syntax:
my_tuple = (10, 20, 30)
single_element_tuple = (10,) # A comma is required for a single-
element tuple
Can Tuple Elements Be Changed?
No, tuple elements cannot be changed or updated because tuples
are immutable. This means once a tuple is created, its elements
cannot be modified, added, or removed.
Justification:
• Tuples are stored in a way that prevents modification,
ensuring data integrity.
• Any attempt to change a tuple’s elements results in an error:
Example:
my_tuple = (10, 20, 30)
my_tuple[1] = 50 # TypeError: 'tuple' object does not support
item assignment
However, if a tuple contains mutable elements (e.g., lists), those
elements can be modified.
Example:

P a g e 8 | 21
Python Assignment

my_tuple = (10, [20, 30], 40)


my_tuple[1][0] = 50 # Modifying the list inside the tuple
print(my_tuple) # Output: (10, [50, 30], 40)
Thus, tuples are immutable, but mutable objects inside a tuple
can be modified.

P a g e 9 | 21
Python Assignment

6. How do you declare a set? Can we iterate through a set by


using a loop? Justify your answer.
Sets in Python
Declaring a Set
A set in Python is declared using curly braces {} or the set()
function. Sets are unordered collections of unique elements.
Syntax:
my_set = {10, 20, 30} # Using curly braces
empty_set = set() # Creating an empty set (NOT `{}` which
creates an empty dictionary)
Can You Iterate Through a Set?
Yes, you can iterate through a set using a loop. Since sets are
iterable, a for loop can be used to access each element.
Example:
my_set = {10, 20, 30, 40}

for item in my_set:


print(item)
Output (Order may vary due to unordered nature of sets):
10
20
30
40
Justification

P a g e 10 | 21
Python Assignment

• Sets are iterable, allowing iteration using loops like for and
while.
• Since sets are unordered, the iteration order is not
guaranteed to match the insertion order.
Thus, sets can be iterated, but the order of elements is
unpredictable.

P a g e 11 | 21
Python Assignment

7. Explain the following set operations:


a) set union
b) set intersection
c) set difference
d) set symmetric difference
Set Operations in Python
Python provides built-in set operations for mathematical
computations. Below are the key operations:
a) Set Union (| or union())
The union of two sets combines all unique elements from both
sets.
Syntax:
A|B
A.union(B)
Example:
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Output: {1, 2, 3, 4, 5}

b) Set Intersection (& or intersection())


The intersection of two sets returns elements common to both
sets.
Syntax:
A&B

P a g e 12 | 21
Python Assignment

A.intersection(B)
Example:
A = {1, 2, 3}
B = {3, 4, 5}
print(A & B) # Output: {3}

c) Set Difference (- or difference())


The difference of two sets returns elements in A but not in B.
Syntax:
A-B
A.difference(B)
Example:
A = {1, 2, 3}
B = {3, 4, 5}
print(A - B) # Output: {1, 2}

d) Set Symmetric Difference (^ or symmetric_difference())


The symmetric difference returns elements in either set but not
in both.
Syntax:
A^B
A.symmetric_difference(B)
Example:
A = {1, 2, 3}
P a g e 13 | 21
Python Assignment

B = {3, 4, 5}
print(A ^ B) # Output: {1, 2, 4, 5}
Summary:
Operation Symbol Function Result
Union ` ` A.union(B)
Intersection & A.intersection(B) Common
elements in
both sets
Difference - A.difference(B) Elements
in A but
not in B
Symmetric ^ A.symmetric_difference(B) Elements
Difference in either A
or B, but
not both

P a g e 14 | 21
Python Assignment

8. How do you declare a dictionary in Python?


Declaring a Dictionary in Python
A dictionary in Python is declared using curly braces {} or the
dict() function. It stores data in key-value pairs, where each key
is unique.
Syntax:
my_dict = {key1: value1, key2: value2, ...}
Examples:
1. Using Curly Braces {} (Preferred Method)
student = {"name": "Alice", "age": 20, "course": "Computer
Science"}
2. Using the dict() Constructor
student = dict(name="Alice", age=20, course="Computer Science")
3. Empty Dictionary
empty_dict = {}
Dictionaries allow quick lookups using keys and support dynamic
modifications.

P a g e 15 | 21
Python Assignment

9. Explain how to access dictionary elements using indexes


or keys, with examples.
Accessing Dictionary Elements in Python
Dictionary elements are accessed using keys, as dictionaries store
data in key-value pairs.
Methods to Access Elements:
1. Using Square Brackets [] (Raises KeyError if key is
missing)
student = {"name": "Alice", "age": 20, "course": "CS"}
print(student["name"]) # Output: Alice
2. Using get() Method (Returns None if key is missing,
avoiding errors)
print(student.get("age")) # Output: 20
print(student.get("grade")) # Output: None (key not found)
Key Differences

Method Behavior when Key is Missing

[] Raises KeyError

get() Returns None (or a default value if provided)


Using get() is safer when dealing with unknown keys.

P a g e 16 | 21
Python Assignment

10. Explain the use of the `update()` function with respect to a


dictionary.
Dictionary update() Function in Python
The update() function is used to merge another dictionary or
key-value pairs into an existing dictionary. It modifies the
dictionary in place by adding new key-value pairs or updating
existing keys.
Syntax:
dict1.update(dict2) # Merges dict2 into dict1
dict1.update(key=value) # Adds/updates a single key-value pair
Examples:
1. Updating with Another Dictionary
student = {"name": "Alice", "age": 20}
new_data = {"age": 21, "course": "CS"}
student.update(new_data)
print(student)
# Output: {'name': 'Alice', 'age': 21, 'course': 'CS'}
(age is updated, course is added.)
2. Updating with Key-Value Pairs
student.update(grade="A", city="New York")
print(student)
# Output: {'name': 'Alice', 'age': 21, 'course': 'CS', 'grade': 'A', 'city':
'New York'}
Key Points:
• Updates existing keys if they are present.

P a g e 17 | 21
Python Assignment

• Adds new keys if they do not exist.


• Can accept another dictionary or keyword arguments.

P a g e 18 | 21
Python Assignment

11. Explain different ways and functions to remove key-value


pairs from a dictionary.
Removing Key-Value Pairs from a Dictionary in Python
Python provides multiple ways to remove key-value pairs from a
dictionary:
1. Using pop(key) (Recommended)
Removes the specified key and returns its value. Raises KeyError
if the key is missing (unless a default is provided).
student = {"name": "Alice", "age": 20, "course": "CS"}
age = student.pop("age")
print(student) # Output: {'name': 'Alice', 'course': 'CS'}
print(age) # Output: 20
2. Using del Statement
Deletes a key-value pair but raises KeyError if the key does not
exist.
del student["course"]
print(student) # Output: {'name': 'Alice'}
3. Using popitem()
Removes and returns the last inserted key-value pair (useful for
LIFO deletion). Raises KeyError if the dictionary is empty.
pair = student.popitem()
print(pair) # Output: ('name', 'Alice')
print(student) # Output: {}
4. Using clear()
Removes all key-value pairs, making the dictionary empty.

P a g e 19 | 21
Python Assignment

student.clear()
print(student) # Output: {}
Key Differences:
Method Removes Returns Raises Error if Key
Value is Missing?
pop(key) Specific key Yes Yes (unless
default provided)
del Specific key No Yes
dict[key]
popitem() Last inserted Yes Yes (if empty)
key (Tuple)
clear() All keys No No
Each method is useful based on the specific removal requirement.

P a g e 20 | 21
Python Assignment

12. How do you declare a list?


Declaring a List in Python
A list in Python is declared using square brackets [] or the list()
constructor. It can store multiple values of different data types
and allows modifications.
Syntax:
my_list = [item1, item2, item3, ...] # Using square brackets
my_list = list(iterable) # Using the list() constructor
Examples:
1. Declaring a List with Values
fruits = ["apple", "banana", "cherry"]
2. Declaring an Empty List
empty_list = []
3. Using the list() Constructor
numbers = list((1, 2, 3)) # Converts a tuple to a list
4. List with Mixed Data Types
mixed_list = ["Alice", 25, True, 3.5]
Lists are mutable, meaning elements can be added, removed, or
modified dynamically.

P a g e 21 | 21

You might also like