Why Range() does not include last or end element ? Is it possible to include last element of range?

** Please check this question and give me an another way to this solve this problem. I had used the range in for loop but it could not able to include last element. So i had solved the problem but i want an another way to solve.

Create a function named remove_middle which has three parameters named lst , start , and end .

The function should return a list where all elements in lst with an index between start and end (inclusive) have been removed.

For example, the following code should return [4, 23, 42] because elements at indices 1 , 2 , and 3 have been removed:**

Here’s the Questions Exercise : https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-lists

def remove_middle(lst,start,end):
for i in range(start, end):
lst.pop(i)
s = end - start - 1
lst.pop(s)
return lst

#Uncomment the line below when your function is done
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))

You can use index slices. For example

some_list = m = [0,2,4,6,8,10,12,14]
print(some_list[2:6])
#>> [4, 6, 8, 10]

In response to your question of including a last element of range I’m assuming you mean as to something like [a:b] excludes the last element (in this case b). You can always right b+1 in situations like these to include the excluded element. Still, I’m not sure if that’s what you’re asking so it’s hard to say.

4 Likes

I also know that but i am asking that is their any way to inclue last element in range without increasing the last element.
i.e. if we had to print 1 to 10
then we use range(1, 11) but i am saying that without increasing it is their anyway.

The simple answer is no. When designing these languages, these are choices that the designers have to make. For example, in R, indices begin at 1 instead of 0. When trying to make these decisions, a good design will take into account:

  1. the aim of the program
  2. the expectations of the user-base
  3. the practicality of implementation

For example, having range(1,10) produce 1-10 is convenient from a visual perspective, but in common indexing operations it makes more sense to have it be the way it is. For example:

for i in range(0, len(example_list))

This type of for loop that cycles through all indices in the length of a list is a bread-and-butter tool in python and in this format you don’t have to add any extra operators (like +1).

4 Likes

Ok, I understand ! Thanks for ur quick reply :slight_smile:. It’s a bless for me to having in a good community.

1 Like