Python – Change Items

In Python, changing items in data structures like lists, tuples, dictionaries, and sets varies based on whether the data structure is mutable or immutable. Here’s how you can change items in different structures:


1. Changing Items in a List

Lists are mutable, meaning you can change, add, or remove elements after the list is created.

Changing an Existing Item:

You can change an item by accessing it using its index and assigning a new value.

Example:

my_list = [10, 20, 30, 40, 50]

# Change the item at index 2 (third item)
my_list[2] = 99
print(my_list)  # Output: [10, 20, 99, 40, 50]

Changing Multiple Items:

You can also use slicing to change multiple items at once.

my_list[1:4] = [21, 22, 23]
print(my_list)  # Output: [10, 21, 22, 23, 50]

2. Changing Items in a Tuple

Tuples are immutable, meaning their elements cannot be changed directly after creation. However, you can create a new tuple based on the existing one with changes.

Example:

my_tuple = (10, 20, 30, 40, 50)

# Tuples are immutable, so you can't do this:
# my_tuple[2] = 99  # This will raise an error

# Instead, create a new tuple
new_tuple = my_tuple[:2] + (99,) + my_tuple[3:]
print(new_tuple)  # Output: (10, 20, 99, 40, 50)

3. Changing Items in a Set

Sets are mutable, but they are unordered collections, meaning you can’t access or change items directly by index. However, you can add or remove elements.

Example 1: Removing and Adding an Item

my_set = {10, 20, 30, 40, 50}

# Remove an element
my_set.remove(30)  # If 30 doesn't exist, this will raise a KeyError

# Add a new element
my_set.add(60)
print(my_set)  # Output: {10, 20, 40, 50, 60}

Example 2: Using discard() (no error if the element does not exist)

my_set.discard(100)  # No error, even though 100 is not in the set

4. Changing Items in a Dictionary

Dictionaries are mutable, and you can change the value of a specific key by directly accessing the key and assigning a new value.

Example:

my_dict = {'a': 10, 'b': 20, 'c': 30}

# Change the value associated with key 'b'
my_dict['b'] = 99
print(my_dict)  # Output: {'a': 10, 'b': 99, 'c': 30}

Adding or Updating Items:

You can also add new key-value pairs or update existing ones.

# Add a new key-value pair
my_dict['d'] = 40
print(my_dict)  # Output: {'a': 10, 'b': 99, 'c': 30, 'd': 40}

# Update multiple keys
my_dict.update({'a': 11, 'c': 31})
print(my_dict)  # Output: {'a': 11, 'b': 99, 'c': 31, 'd': 40}

Summary of Changing Items:

  • Lists: You can change elements by accessing them via index and assigning a new value.
  • Tuples: Cannot be changed directly; you must create a new tuple.
  • Sets: Cannot be accessed by index, but you can add or remove elements.
  • Dictionaries: You can change values associated with keys, add new key-value pairs, or update multiple pairs.
Leave a Reply 0

Your email address will not be published. Required fields are marked *