Home > OS >  How can I substitute a list by index in python?
How can I substitute a list by index in python?

Time:10-07

I need to write a function that contains 3 input parameters:

  • A list called randome containing random integer numbers

  • A list called indexes that contains (non-negative) indexes of items that need substitution by the third parameter. It is possible that indexes contains non-existent indexes for source. Check if the index actually exists in source before you substitute. Perhaps using the len of randome?

  • A value new_value that we use to overwrite the items in source. Assign True as default value.

For example: substitution_function([1, 2, 3, 4, 5], [0, 2], True) must return this list: [True, 2, True, 4, 5]

Anyone have any ideas?

def substitution_function(randome, indexes, new_value=True):

    result = []
    for data in indexes:
        if data <= len(source):
            result.append(new_value)
        else:
            for i in range(len(source)):
                result.append(source[i])    
    return result

But this code can be greatly improved

CodePudding user response:

The way you started is strange, let's start from scratch. There is 2 ways

  1. Replace with the given value, at the given indexes

    def substitution_function(source, indexes, new_value=True):
        for index in indexes:
            if index < len(source):
                source[index] = new_value
        return source
    
  2. Build a whole new list, and conditionally use original value or replacement one

    # that solution is safe-proof to invalid index
    def substitution_function(source, indexes, new_value=True):
        result = []
        indexes = set(indexes) # can be added in case of large list
        for i, data in enumerate(source):
            if i in indexes:
                result.append(new_value)
            else:
                result.append(data)
        return result
    

CodePudding user response:

I think it's better to you read the Stack Overflow Guidelines

  • Related