Basic_Operations_With_Examples_Python_Lists_Tuples_Sets_With_Dictionaries
Basic_Operations_With_Examples_Python_Lists_Tuples_Sets_With_Dictionaries
1. List Operations:
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
Example:
my_list = [1, 2, 3]
result = my_list * 3
- Accessing Elements: Use indexing (e.g., list[0], list[-1]) to access list items.
Example:
print(my_list[0]) # Output: 10
print(my_list[-1]) # Output: 40
Example:
result = my_list[1:4]
print(result) # Output: [20, 30, 40]
Example:
Example:
my_list.append(40)
Example:
my_list.insert(1, 15)
Example:
my_list.remove(20)
removed_item = my_list.pop(1)
print(removed_item) # Output: 30
print(my_list) # Output: [10, 40]
Example:
my_list.sort()
Example:
my_list.reverse()
reversed_list = my_list[::-1]
Example:
my_list.clear()
print(my_list) # Output: []
2. Tuple Operations:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
Example:
my_tuple = (1, 2, 3)
result = my_tuple * 3
Example:
Example:
count = my_tuple.count(20)
print(count) # Output: 2
- Finding Index: Use index() method to find the first occurrence of an item.
Example:
print(index) # Output: 2
3. Set Operations:
Example:
my_set.add(40)
Example:
my_set.remove(20)
Example:
Example:
set1 = {10, 20, 30}
result = set1.union(set2)
Example:
result = set1.intersection(set2)
- Difference: Find elements in one set but not another using difference() or - operator.
Example:
result = set1.difference(set2)
- Creating a Dictionary:
Example:
my_dict = {"name": "Alice", "age": 25, "city": "Pune"}
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'Pune'}
- Accessing Values:
Example:
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 25
- Removing Items:
Example:
my_dict.pop("city")
print(my_dict)
# Output: {'name': 'Alice', 'age': 26, 'country': 'India'}
del my_dict["age"]
print(my_dict)
# Output: {'name': 'Alice', 'country': 'India'}
- Checking Membership:
Example:
print("name" in my_dict) # Output: True
print("city" in my_dict) # Output: False