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

Unit II

Unit II covers data structures in Python, including Lists, Tuples, Sets, and Dictionaries. Lists are mutable collections that can store different data types, while Tuples are immutable collections. Sets are unordered collections of unique elements, and Dictionaries are key-value pairs that allow for efficient data retrieval.

Uploaded by

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

Unit II

Unit II covers data structures in Python, including Lists, Tuples, Sets, and Dictionaries. Lists are mutable collections that can store different data types, while Tuples are immutable collections. Sets are unordered collections of unique elements, and Dictionaries are key-value pairs that allow for efficient data retrieval.

Uploaded by

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

Unit II: Data Structures in Python

2.1 List
What is a List?
• A List is a collection of ordered, mutable
(changeable) elements.
• Lists can store items of different data types —
integers, strings, even other lists.
• Lists are defined using square brackets [ ].

Creating a List
my_list = [10, 20, 30, "Python", 4.5]
print(my_list)
Output:
[10, 20, 30, 'Python', 4.5]

Accessing List Elements


Use indexing to access elements. Index starts from 0.
print(my_list[0]) # 10
print(my_list[-1]) # 4.5 (last element)
Updating List Elements
Lists are mutable — so we can change values.
my_list[1] = 25
print(my_list) # [10, 25, 30, 'Python', 4.5]

Deleting Elements
You can delete an element using del, pop(), or
remove().
del my_list[0] # Deletes by index
my_list.pop() # Removes last item
my_list.remove(30) # Removes value 30

Basic List Operations


list1 = [1, 2, 3]
list2 = [4, 5]

print(list1 + list2) # [1, 2, 3, 4, 5] (concatenation)


print(list1 * 2) # [1, 2, 3, 1, 2, 3] (repetition)
print(2 in list1) # True (membership)
🛠 Common List Methods
Method Description Example
append(x) Adds element to end list1.append(6)
list1.insert(1,
insert(i,x) Inserts at index i
10)
Removes first occurrence
remove(x) list1.remove(2)
of value x
Removes and returns item
pop(i) list1.pop(0)
at index i
Sorts the list in ascending
sort() list1.sort()
order
reverse() Reverses the list list1.reverse()
Returns number of
len() len(list1)
elements
2.2 Tuple
What is a Tuple?
• A Tuple is an ordered, immutable collection of
elements.
• Once a tuple is created, its elements cannot be
changed.
• Tuples are defined using parentheses ().
• Useful when you want to protect data from being
modified.

Creating a Tuple
my_tuple = (10, 20, 30, "Python", 5.5)
print(my_tuple)
Output:
(10, 20, 30, 'Python', 5.5)

Accessing Tuple Elements


Use indexing like lists.
print(my_tuple[0]) # 10
print(my_tuple[-1]) # 5.5
Immutability of Tuples
my_tuple[1] = 25 # Error! Tuples cannot be
changed

Basic Tuple Operations


tuple1 = (1, 2, 3)
tuple2 = (4, 5)

print(tuple1 + tuple2) # (1, 2, 3, 4, 5)


print(tuple1 * 2) # (1, 2, 3, 1, 2, 3)
print(2 in tuple1) # True

🛠 Common Tuple Methods


Method Description Example
Returns number of elements
len() len(tuple1)
in the tuple
Returns number of times x
count(x) tuple1.count(2)
occurs
Returns index of first
index(x) tuple1.index(3)
occurrence of x
Tuple Packing and Unpacking
# Packing
person = ("Aarti", 20, "Pune")

# Unpacking
name, age, city = person
print(name) # Aarti
print(city) # Pune
2.3 Set
What is a Set?
• A Set is an unordered collection of unique and
immutable elements.
• Defined using curly braces {} or the set()
constructor.
• Duplicates are automatically removed.
• Sets are mutable, but the elements must be
immutable (e.g., numbers, strings, tuples).

Creating a Set
my_set = {1, 2, 3, 4, 4, 5}
print(my_set)
Output:
{1, 2, 3, 4, 5} → (Duplicate 4 is removed)
empty_set = set() # Correct way to create an empty set

Accessing and Modifying Sets


• Sets do not support indexing (unordered).
• You can add or remove elements.
my_set.add(6) # Add element
my_set.remove(3) # Remove element (raises error if
not found)
my_set.discard(10) # Remove element (no error if not
found)

Set Operations
a = {1, 2, 3}
b = {3, 4, 5}

print(a | b) # Union → {1, 2, 3, 4, 5}


print(a & b) # Intersection → {3}
print(a - b) # Difference → {1, 2}
print(a ^ b) # Symmetric Difference → {1, 2, 4, 5}

🛠 Built-in Set Methods


Method Description Example
Adds item x to
add(x) my_set.add(10)
the set
Removes item x;
remove(x) my_set.remove(2)
error if not found
Method Description Example
Removes item x;
discard(x) no error if not my_set.discard(20)
found
Combines two
union(set2) `)
sets (also `
Returns common
intersection(set2) a.intersection(b)
elements (also &)
Items in a but
difference(set2) a.difference(b)
not in b (also -)
Removes all
clear() elements from my_set.clear()
the set
2.4 Dictionary

What is a Dictionary?
• A Dictionary is an unordered collection of data in
key-value pairs.
• Each key is unique, and keys are used to access
values.
• Defined using curly braces {} or the dict()
constructor.

Creating a Dictionary
student = {
"name": "Ashwini",
"age": 20,
"city": "Pune"
}
empty_dict = dict()

Accessing Values
print(student["name"]) # Ashwini
print(student.get("age")) # 20
Updating and Deleting Elements
student["age"] = 21 # Update
student["email"] = "[email protected]" # Add new key-
value
del student["city"] # Delete key
student.pop("email") # Remove key using pop()

🛠 Common Dictionary Methods


Method Description Example
Returns a list of
keys() student.keys()
all keys
Returns a list of
values() student.values()
all values
Returns all key-
items() value pairs as student.items()
tuples
Returns value for
get(key) student.get("name")
the given key
student.update({"age":
update(dict2) Updates
dictionary with 22})
Method Description Example
key-value pairs
from another
Removes
pop(key) student.pop("name")
specified key
Removes all
clear() student.clear()
items

Looping through Dictionary


python
CopyEdit
for key, value in student.items():
print(key, ":", value)

You might also like