Home > Software design >  Replace an item in a list by another item
Replace an item in a list by another item

Time:05-16

I have to replace in a list the multiples of 5 by the number x. For example, if I have the list [1,3,5,7,9,9,11,13,15,17,19,21,23,25,27,29], the result has to be [1,3,5x,7,9,11,13,15x,17,19,21,23,25x,27,29]. I have tried to develop the script but it doesn't work, can anyone help me?

numbers = list (range(1,31))

odds = [number for number in numbers if number % 2 == 1]

print(odds)

for index, value in enumerate(odds):
   
    if value%5==0:
        odds[index] = '5x'

print(odds)

CodePudding user response:

We can solve your problem by using the value variable, which stores the current number. We just need to reference this variable when setting the current element to add to "x", like this:

odds[index] = str(value)   "x"

Notice the need to cast value as a string, as we cannot concatinate an integer and a string without creating a touple.

CodePudding user response:

You can make it much simpler:

numbers = range(1, 31, 2)
res = [str(i)   'x' if i%5 == 0 else i for i in numbers]
print(res)

Result:

[1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]

Explanation:

  1.  numbers = range(1, 31, 2)
    

    This creates an iterable with odd numbers from 1 to 29 without having to do:

    numbers = list(range(1,31))
    odds = [number for number in numbers if number % 2 == 1]
    

    which is redundant. The syntax for the range function is range(start, stop, step), so for odd numbers from 1 to 30, it'll be range(1, 31, 2) which will give 1, 3, 5, 7, and so on.

  2. res = [str(i)   'x' if i%5 == 0 else i for i in numbers]
    

    I'm assuming you know how to use list comprehensions since you've used it in your code. The above line of code simply searches for a value that is divisible by 5 and adds an x to this value, else it simply adds i to the list.

    You can also use f-strings instead of str(i) x (as Lancelot suggests under Jensen's answer):

    res = [f'{i}x' if i%5 == 0 else i for i in numbers]
    
  • Related