Python Lists - Change List Items
Python lists can store an ordered collection of items, or elements, of varying types. They are often used to compile multiple items into a single, mutable variable, which is helpful for retrieving items, specifying outputs or performing calculations quickly. Lists are also a type of built-in data structure in Python (along with tuples, sets and dictionaries), which is a specified way of storing and formatting data.
Lists in Python are mutable meaning their items can be changed after the list is created. Modifying elements in a list is a common task, whether we're replacing an item at a specific index, updating multiple items at once, or using conditions to modify certain elements. This article explores the different ways to change a list item with practical examples.
List is a mutable data type in Python. It means, the contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list.
1-Change Item Value
To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
2-Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
3-Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method inserts an item at the specified index:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
Информация по комментариям в разработке