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

Time:04-13

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.

CodePudding user response:

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:]

CodePudding user response:

def remove_range(array, from_index, to_index):
    new = []
    i = 0
    while(i < len(array)):
        i  = 1
        if i < from_index] or i >= to_index:
            new.append(array[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))```
  • Related