Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing all elements of a list between indexes without using inbuilt python functions

def remove_range(array, from_index, to_index):
    new = []
    for i in array:
        if i < array[from_index] or i >= array[to_index]:
            new.append(i)
    return new

array = [9, 2, 2, 4, 6]

from_index = int(input("Enter a starting point: "))
to_index = int(input("Enter an end point: "))

print(remove_range(array, from_index, to_index))

The goal here is to remove all elements between two indexes from a list (including the first index but excluding the second one). Above you see what I have tried doing so far and it does not seem to work. I think it has something to do with me comparing numbers to numbers instead of indexes to indexes. However, I have no idea how to put this into practice correctly right now. Can anyone help?

Edit: any inbuilt python functions for lists aside from append are not allowed. Using square brackets is obviously fine, but I would like to avoid using the colon.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your code, i is not an index. It is an array element. If you want to do logic based on the indices, use an explicit index. For example:

def remove_range(array, from_index, to_index):
    new = []
    for i in range(len(array)):
        if i < from_index or i > to_index:
            new.append(array[i])
    return new

array = [9, 2, 2, 4, 6]
from_index = 1
to_index = 3
print(remove_range(array, from_index, to_index)) # [9, 6]

Usually, explicit indices are provided via enumerate() though:

def remove_range(array, from_index, to_index):
    new = []
    for i, el in enumerate(array):
        if i < from_index or i > to_index:
            new.append(el)
    return new

The whole thing could be written more concisely as a list comprehension:

def remove_range(array, from_index, to_index):
    return [e for i, e in enumerate(array) if i < from_index or i > to_index]

But even better is to use slicing and list concatenation with +:

def remove_range(array, from_index, to_index):
    return array[:from_index] + array[from_index+to_index:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading