- 2

LISTS. (Muttable vs immutable) in python

a=[5,6,9,8,[4,5],'willy',1,0] a[5][2]=0 the out put shows error because strings are immutable. but LIST are mutable So why error. can any one justify other than definition?

25th Apr 2018, 4:58 PM
Kesava N
Kesava N - avatar
14 Answers
+ 4
If you want to replace a letter in a word in a list, check my code. It leaves the list intact, but 'willy' becomes 'wi0ly'. https://code.sololearn.com/cm7iNquLt35Z/?ref=app
25th Apr 2018, 6:11 PM
Johannes
Johannes - avatar
+ 3
Try this: a=[5,6,9,8,[4,5],'willy',1,0] a[5]=0 print(a) # output: [5, 6, 9, 8, [4, 5], 0, 1, 0]
25th Apr 2018, 5:47 PM
David Ashton
David Ashton - avatar
+ 2
:) thanks kesava - for future reference: very often, it's easier to understand a question when you include the current and the desired output, e. g 'willy' >> 'wi0ly'
25th Apr 2018, 6:25 PM
Johannes
Johannes - avatar
+ 2
It's done - check your other question, I posted the code there.
25th Apr 2018, 6:46 PM
Johannes
Johannes - avatar
+ 1
Remember indexing starts at 0. Your first index [5] is actually pointing at the sixth element. if youre trying to change the second element of the fifth element (5) in your list within a list you want it to look like: a[4][1]=0 Cheers mate! đŸ€™đŸ»
25th Apr 2018, 5:24 PM
Jacob Matini
Jacob Matini - avatar
+ 1
it time for thumb's up johannes
25th Apr 2018, 6:18 PM
Kesava N
Kesava N - avatar
+ 1
Sure, what have you got so far?
25th Apr 2018, 6:35 PM
Johannes
Johannes - avatar
0
your question is unclear. if you know that strings are immutable then whats the question? if youre trying to change one character in your string you would need to convert it to a list of all of the characters or else use a str method
25th Apr 2018, 5:32 PM
Jacob Matini
Jacob Matini - avatar
0
it is possible with a simple string method or re.sub...
25th Apr 2018, 5:53 PM
Jacob Matini
Jacob Matini - avatar
0
k, can u help me with the other question I posted regarding largest consequtive number in a string
25th Apr 2018, 6:27 PM
Kesava N
Kesava N - avatar
0
input='12jhon345willy3456hans56789kathy' need output as largest consequtive number. like 56789
25th Apr 2018, 6:36 PM
Kesava N
Kesava N - avatar
- 1
ur total unaware of what I am asking. i want replace charector in 'willy' string not in [4,5].
25th Apr 2018, 5:29 PM
Kesava N
Kesava N - avatar
- 1
yes strings are immutable but lists are MUTABLE. so I.e what I am asking justify
25th Apr 2018, 5:34 PM
Kesava N
Kesava N - avatar
- 1
see what I am asking is not possible i don't want to replace entire string.
25th Apr 2018, 5:50 PM
Kesava N
Kesava N - avatar