Home > Software design >  How to get '7' attached to each string in a list in Python if it doesn't have 7 alrea
How to get '7' attached to each string in a list in Python if it doesn't have 7 alrea

Time:11-23

I have been trying to solve a problem where I am given a list as input and I need to show an output with 7 attached to each string value if it doesn't contain a 7 already.

I have created a list and for the case of 7 not included I have attached the '7' using the for loop. So for example: for the input ["a7", "g", "u"], I expect output as ["a7","g7","u7"] but I am getting the output as follows
['a7', 'g', 'u', ['a77', 'g7', 'u7']]

I have tried to put the values in a new list using append but I am not sure how to remove the old values and replace it with new ones in existing list. Following is my code

class Solution(object):
    def jazz(self, list=[]):

        for i in range(len(list)):
            if '7' not in list[i]:
                li = [i   '7' for i in list]
                list.append(li)
                return list


if __name__ == "__main__":
    p = Solution()
    lt = ['a7', 'g', 'u']
    print(p.jazz(lt))

CodePudding user response:

You can use a cleaner and more pythonic solution, no classes required, and much more concise:


def jazz(items):
    return [item if '7' in item else item '7' for item in items]

if __name__ == "__main__":
    lt = ['a7', 'g', 'u']
    p = jazz(lt)
    print(p)

If you want to modify the original list you can use:

if __name__ == "__main__":
    lt = ['a7', 'g', 'u']
    lt[:] = jazz(lt)
    print(lt)

CodePudding user response:

@AviTurner already showed you the simplest way of doing it. I'm just gonna write some point about your solution:

  • You don't need to inherit from object in Python 3. check here
  • Don't use mutable objects for your parameters' default values unless you know what you're doing. check here.
  • Don't use built-in names like list for your variables.
  • You create a list li and then you append that, This appends the whole list as a single item. Instead you either want to append individual items or .extend() it.
  • It's perfectly ok to iterate this way for i in range(len(something)) but there is a better approach, if you need only the items, you can directly get those items this way : for item in something. If you also need the indexes: for i, item in enumerate(something)
  • Related