Manipulating Lists and Tuples
Lists, tuples, and sets are three common data structures in Python used to store collections of items. Each has its own characteristics and methods for manipulation. Let's explore how to manipulate lists and tuples in Python programming:
Lists: A list is a mutable collection of items, and it is defined using square brackets []. Lists can hold items of different types and allow for modifications after creation.
- Creating Lists:my_list = [1, 2, 3, 4, 5]
- Accessing Elements:first_item = my_list[0] # Access the first item (indexing starts from 0) last_item = my_list[-1] # Access the last item
- Modifying Elements:my_list[2] = 10 # Modify an element at a specific index
- Adding Elements:my_list.append(6) # Add an item to the end my_list.insert(2, 7) # Insert an item at a specific index
- Removing Elements: my_list.pop() # Remove and return the last item my_list.remove(3) # Remove the first occurrence of a specific item
Tuples: A tuple is an immutable collection of items, and it is defined using parentheses (). Tuples cannot be modified after creation.
领英推è
- Creating Tuples:my_tuple = (1, 2, 3, 4, 5)
- Accessing Elements:first_item = my_tuple[0] last_item = my_tuple[-1]
- Note: Tuples do not support item assignment or modification.
Sets: A set is an unordered collection of unique items, and it is defined using curly braces {} or the set() constructor.
- Creating Sets:my_set = {1, 2, 3, 4, 5}
- Adding and Removing Elements:my_set.add(6) # Add an item my_set.remove(3) # Remove a specific item; raises an error if not found my_set.discard(2) # Remove a specific item; does nothing if not found
- Operations on Sets;union_set = set1.union(set2) # Union of two sets intersection_set = set1.intersection(set2) # Intersection of two sets
Remember that lists are mutable, tuples are immutable, and sets store unique items without any specific order. Depending on your use case, you can choose the appropriate data structure for your needs.