Homesand
Homesand

Reputation: 423

Replacement of element in a list of python

I am quite new with python and I try to replace the elements of a list with x given the specific list has the same elements. For example:

list =[1,2,3,4,5,6,7,8,9]
a = [1,4,7,9]

The list should become like:

list =[x,2,3,x,5,6,x,8,x]

Upvotes: 0

Views: 85

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

rebuild your list using list comprehension, and a ternary to decide whether keep the original element or the replacement:

lst = [1,2,3,4,5,6,7,8,9]
a = {1,4,7,9}

result = ["x" if i in a else i for i in lst]

which yields:

['x', 2, 3, 'x', 5, 6, 'x', 8, 'x']

note that it's better if a is a set in the general case, where there's a lot of elements, so the lookup is faster than on a list.

notes:

  • don't use list as a variable name as it shadows the list type. I used lst as you noticed
  • this method creates another list, if you want to modify lst, assign to lst instead of result (a classical loop is also possible instead of the comprehension)

Upvotes: 5

Sam Goodin
Sam Goodin

Reputation: 78

You could use a for loop within a while loop to do this.

counter = 0
while counter < len(list):
    for x in a:
        if list[counter] == x:
            list[counter] = "x"
    counter += 1

Upvotes: 0

Related Questions