'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.
Solution 1:[1]
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:]
Solution 2:[2]
Comparing the elements in the list is not a good idea to achieve your. So just create a int variable named i and increment it in each loop by one. And use that to compare with from_index and to_index.
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))```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
