Hamzah Akhtar
Hamzah Akhtar

Reputation: 525

Change the value of a list's element

I have created a list holding various values. However i wanted to know how i could update/replace a piece of data in a list of a specific position. For example if i had a list as follows: [hello, goodbye, welcome, message] and i wanted to replace the string in position 2 with the following string: 'wave'. how would i do that?? i tried the code below, but it shifts the values to the right and inserts a new piece of data where the position is given:

MyList = ['hello', 'goodbye', 'welcome', 'message']
MyList.insert(2, 'wave')

Upvotes: 0

Views: 63

Answers (1)

wnnmaw
wnnmaw

Reputation: 5514

Lists are mutable, which means you can alter them in place. Therefore you can simple assign a new value to index 2:

>>> lst = range(10)
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[2] = "new value"
>>> lst
[0, 1, 'new value', 3, 4, 5, 6, 7, 8, 9]

dicts are also mutable:

>>> d = {1:'a',2:'b'}
>>> d[2] = "new value"
>>> d
{1: 'a', 2: 'new value'}

However, strings and tuples ARE NOT. You can iterate through them which sometimes causes confusion, (especially the sub-string notation vs. slicing)

>>> aString = "Hello, my name is Dave"
'my '
>>> aString[7:9]
'my'
>>> aString[7:9] = "MY"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Similarly,

>>> tup = (1,2,3)
>>> tup[0]
1
>>> tup[0] = 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

For strings, you can "cheat" by converting them into a list (split()), mutating them, then putting them back into a string (join()), but this is not actual mutation of the string in place

Upvotes: 4

Related Questions