Lists,Tuple, Set, Dictionary
Lists
A list is a collection of items stored in one variable.
Lists are ordered, changeable (mutable), and allow duplicates.
Example:
fruits = ["apple", "banana", "mango"]
1. Creating a List
numbers = [10, 20, 30]
names = ["Aruna", "Kavi", "Sona"]
mixed = [10, "hello", 3.14, True]
2. Accessing List Items (Indexing)
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
print(fruits[2]) # mango
**Negative Index:
**print(fruits[-1]) # mango
print(fruits[-2]) # banana
3. List Slicing
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[:3]) # [10, 20, 30]
print(nums[2:]) # [30, 40, 50]
4. Changing List Items
fruits[1] = "grape"
5. List Functions
append() – add at end
fruits.append("orange")
insert() – add at position
fruits.insert(1, "kiwi")
remove()
fruits.remove("banana")
pop() – remove by index
fruits.pop(2)
sort() – ascending
marks = [50, 20, 90]
marks.sort()
reverse()
marks.reverse()
len()
print(len(fruits))
6. Looping Through List
for item in fruits:
print(item)
7. List Comprehension
squares = [x*x for x in range(1, 6)]
print(squares)
TUPLE
A tuple is ordered and unchangeable (immutable).
Example:
days = ("Mon", "Tue", "Wed", "Thu")
Accessing:
print(days[0])
print(days[-1])
Why Tuple?
Fast
Data protection (cannot change)
SET
A set is unordered and stores unique items only.
Example:
nums = {1, 2, 3, 3, 4}
print(nums) # duplicates removed → {1,2,3,4}
Add item:
nums.add(5)
Remove item:
nums.remove(2)
Loop:
for x in nums:
print(x)
DICTIONARY
A dictionary stores data as key–value pairs.
Example:
student = {
"name": "Aruna",
"age": 21,
"course": "Python"
}
Access values:
print(student["name"])
print(student.get("age"))
Add / Update value:
student["place"] = "Chennai"
student["age"] = 22
Remove item:
student.pop("course")
Loop through dictionary:
for key, value in student.items():
print(key, ":", value)
Top comments (0)