Pythonppp
Pythonppp

Reputation: 3

How can I substitute a list by index in python?

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

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

Upvotes: 0

Views: 92

Answers (3)

Dmitriy Neledva
Dmitriy Neledva

Reputation: 864

It runs for loop on randome with getting item's index by enumerate(). If index is in indexes it returns new_value to listcomp's list if it's not it returns item. The possible problem of spare indexes in indexes is solved by just not touching them at all.

def substitution_function(randome, indexes, new_value=True):
    return [new_value if e in indexes else i for e,i in enumerate(randome)]

Upvotes: 0

Isaac Vin&#237;cius
Isaac Vin&#237;cius

Reputation: 21

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

def overwriteArr(arr, idxs, val):
    for idx in idxs:
        try:
            arr[idx] = val
        except:
            pass
    return arr

print(overwriteArr([1, 2, 3, 4, 5], [0, 2], True)) # [True, 2, True, 4, 5]

Upvotes: 0

azro
azro

Reputation: 54148

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
    

Upvotes: 2

Related Questions