Froog
Froog

Reputation: 31

How to edit a specific item in a list in python

list = ["60", "70", "40", "30", "73", "8"]

Here for example, how would i go about

  1. taking an item out of the list (Let's say 40 for example)
  2. performing an operation on it (let's say int(40) - 30))
  3. and then put that item (i.e. '40') back into the list in the position it originally was (3rd)?

The updated list in this case should be:

["60", "70", "10", "30", "73", "8"]

Upvotes: 2

Views: 294

Answers (4)

Luke Yeager
Luke Yeager

Reputation: 1430

If you wanted to replace multiple items, you could do it this way:

myList = [str(int(i)-30) if i=="40" else i for i in myList]

Upvotes: 1

MapReduceFilter
MapReduceFilter

Reputation: 237

Is there a reason for removing it from the list?

y =["60", "70", "40", "30", "73", "8"]
x = int(y[2])
x -= 30
y[2] = str(x)

This feels like it would be the simplist option

Upvotes: 2

Akavall
Akavall

Reputation: 86188

Is this what you are trying to do?

In [2]: List=["60", "70", "40", "30", "73", "8"]

In [3]: List[List.index("40")] = str(int(List[List.index("40")]) - 30)

In [4]: List
Out[4]: ['60', '70', '10', '30', '73', '8']

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174706

I think you mean this.

In [20]: l = ["60", "70", "40", "30", "73", "8"]

In [21]: l[2] = str(int(l[2])-30)

In [22]: l
Out[22]: ['60', '70', '10', '30', '73', '8']

Upvotes: 2

Related Questions