Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing element in list without list comprehension, slicing or using [ ]s

I'm taking this online Python course and they do not like the students using one-line solutions. The course will not accept brackets for this solution.

I already solved the problem using list comprehension, but the course rejected my answer.

The problem reads:

Using index and other list methods, write a function replace(list, X, Y) which replaces all occurrences of X in list with Y. For example, if L = [3, 1, 4, 1, 5, 9] then replace(L, 1, 7) would change the contents of L to [3, 7, 4, 7, 5, 9]. To make this exercise a challenge, you are not allowed to use [].

Note: you don't need to use return.

This is what I have so far, but it breaks because of TypeError: 'int' object is not iterable.

list = [3, 1, 4, 1, 5, 9]

def replace(list, X, Y):
   while X in list:
      for i,v in range(len(list)):
         if v==1:
            list.remove(1)
            list.insert(i, 7)

replace(list, 1, 7)

This was my original answer, but it was rejected.

list = [3, 1, 4, 1, 5, 9]

def replace(list, X, Y):
   print([Y if v == X else v for v in list])

replace(list, 1, 7)

Any ideas on how to fix my longer solution?

like image 530
StacyM Avatar asked Sep 13 '13 00:09

StacyM


People also ask

Can you replace an element in a list?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

How do you use replace in a list?

Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .

How do I replace a character in a list?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

How do you replace multiple elements in a list in Python?

One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.


2 Answers

range() returns a flat list of integers, so you can't unpack it into two arguments. Use enumerate to get index and value tuples:

def replace(l, X, Y):
  for i,v in enumerate(l):
     if v == X:
        l.pop(i)
        l.insert(i, Y)

l = [3, 1, 4, 1, 5, 9]
replace(l, 1, 7)

If you're not allowed to use enumerate, use a plain old counter:

def replace(l, X, Y):
  i = 0
  for v in l:
     if v == X:
        l.pop(i)
        l.insert(i, Y)
     i += 1

l = [3, 1, 4, 1, 5, 9]
replace(list, 1, 7)

Finally, you could use what the authors of the question were probably looking for (even though this is the most inefficient approach, since it linear searches through the list on every iteration):

def replace(l, X, Y):
  for v in l:
     i = l.index(v)
     if v == X:
        l.pop(i)
        l.insert(i, Y)

l = [3, 1, 4, 1, 5, 9]
replace(l, 1, 7)
like image 148
Asad Saeeduddin Avatar answered Oct 16 '22 12:10

Asad Saeeduddin


You can also try this (not using []s or enumerate(), as required):

for i in range(len(l)):  # loop over indices
    if l.__index__(i) == X:  # i.e. l[i] == X
        l.__setitem__(i, Y)  # i.e. l[i] = Y

This probably isn't what the assignment wants you to do, but I'll leave it here for learning purposes.

Note: You shouldn't use list as a variable name since that's already used by a built-in function. I've used l here instead.

like image 29
arshajii Avatar answered Oct 16 '22 12:10

arshajii