0

How a value in a list can be replaced?

Suppose I have the following list :

mylist=[1,3,5,7,4]

and I just want to change the value at index 3 ( which would be 7) with, let's say, 9. (the change is not conditioned )

For earlier versions of python the replace function would work, but how do I do it in Python 3.6?

6
  • 4
    mylist[3] = 9? Commented Oct 22, 2017 at 9:35
  • I've been getting errors with that Commented Oct 22, 2017 at 9:37
  • 2
    What errors? Edit the question to show the message you get. Commented Oct 22, 2017 at 9:38
  • Actually it worked , there was something else wrong, thanks Commented Oct 22, 2017 at 9:39
  • 2
    @Alex12 on what version of Python did list have a replace method? Commented Oct 22, 2017 at 9:40

2 Answers 2

2

Console:

➜ ~ python3
Python 3.6.2 (default, Aug 03 2017, 16:34:42) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist=[1,3,5,7,4]
>>> mylist[3]=9
>>> mylist
[1, 3, 5, 9, 4]
>>>

Just like that.

Sign up to request clarification or add additional context in comments.

Comments

2
>>> mylist = [1,3,5,7,4]

1 . The simplest, go to the list index and assign it the new value.

>>> mylist[3] = 9
>>> mylist
=> [1, 3, 5, 9, 4]

2 . Slicing

>>> mylist = mylist[:3] + [9] + mylist[4:]
>>> mylist
=> [1, 3, 5, 9, 4]

1 Comment

@Alex12 : Sure. Glad to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.