Why and how are selecting python list indexes inclusive and exclusive?

I tried to use delete, because in a previous lesson we were taught the following:
" Emptying a list

There are two ways to empty an existing list. The first way is to just assign the list variable to an empty list. In this case, the old list and its contents are automatically deleted by Python. This is shown in the following code example. list1 = [1, 2, 3, 4, 5, 6, 7 ]
list1 = [ ]
The second method is to use the del() function to delete all the elements of the list. This forces the removal of all the items immediately instead of letting Python delete the contents at some time of its choosing. Both methods produce the same end result which is that the list will be empty of contents.
list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
del list2[:]"

but obviously that command can’t be right with the space between del and list because python hates spaces. can this even work if put in correct syntax?
lst = del(lst[start:end+1]) ?

1 Like
>>> s
'abcdefghijklmnopqrstuvwxyz'
>>> t = list(s)
>>> del(t[7:17])
>>> t
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> ''.join(t)
'abcdefgrstuvwxyz'
>>> 
>>> t = list(s)
>>> del (t[7:17])     # don't leave out the parens; space is not a problem
>>> ''.join(t)
'abcdefgrstuvwxyz'
>>> 
2 Likes

thank you!

I don’t understand this part, though: ‘’.join(t)
I don’t think that was in a lesson yet. what is it supposed to do?

The str.join() method takes a list of strings and concatenates them into a single string. The string object it acts upon is the separator, in this case an empty string.

It can also be used to insert characters into a string…

>>> '-'.join('catnip')
'c-a-t-n-i-p'
>>> 
1 Like

thanks :slight_smile:

2 Likes

This took me a while to figure out. I finally get it now. The +1 at the end is to adjust for the final number “end” to be removed from the function. To some of the other threads, I was tempted to use additional functionality, but I assume there is a method to his madness. This is so far the hardest exercises, primarily because of the wording.

3 Likes

What you need to understand here is that [:start] gets everything UNTIL start (not including start) , and [end:] gets everything FROM end until the end (including end). But since we want to erase the middle, we don’t want to include end.

Here is what I’ve got:

def remove_middle(lst, start, end):
  first = lst[:start]
  second = lst[(end+1):]
  return first + second
3 Likes

How would I know to use ‘+1’ after [end] for this problem? What does adding a ‘+number’ when I’m slicing lists? Hope this makes some sense.

def remove_middle(lst, start, end):
return lst[:start] + lst[end+1:]

Thanks for the help.

If we use end as given, then the new combined string will contain the letter at index end, which we do not want. We need to exclude all the characters between start and end, including the characters at those indices, hence, end + 1.

Sketch it out on paper to give yourself a better picture.

['abcdefg'][start ('h') 'ijklmnopqr' end('s')]['tuvwxyz']
    .. 6            7                    16    17 ..

Recall that a slice excludes the stop index so when we write, str[:7] it gives abcdefg, and when we write, str[17:] it gives tuvwxyz.

The removed substring should be 10 characters long,

len('hijklmnpqr')    # 10
2 Likes

The above post is so full of errors it’s embarrassing.

>>> def remove_middle(lst, start, end):
	return lst[:start] + lst[end:], lst[start:end]

>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> remove_middle(s, 7, 17)
('abcdefgrstuvwxyz', 'hijklmnopq')
>>> a, b = remove_middle(s, 7, 17)
>>> len(a); len(b)
16
10
>>> 

One clearly sees why this question came up. Intuition, or something of that nature. How I plunged headlong in defense with blinders on is my bad. Didn’t feel right afterward so came back for another look see. Lucky I did.

Visualization

>>> def remove_middle(x, h, k):
	return x[:h], x[h:k], x[k:]

>>> l, m, r = remove_middle(s, 7, 17)
>>> '{} {} {}'.format(l, m, r)
'abcdefg hijklmnopq rstuvwxyz'
>>> 

Now we need to get this to work on a list.

>>> l, m, r = remove_middle(list(s), 7, 17)
>>> l + r
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> m
['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']
>>> 
1 Like

Remember that you can select a slice of a list with lst[index1:index2] You can additionally do maths in this selection such as lst[index1:index2 +1]

Basically you are saying we have to do the +1 because the end index is exclusive.

I tackled this problem differently and came up with this:

def remove_middle(lst, start, end):
  lst = lst[:start] + lst[end + 1:]
  return lst

I love what @code_colt has done, converting the end index to a negative value. It took me some time to wrap my head around what you did. Once I got it, I had the exact opposite question: is my code to simple? Are there cases where @code_colt’s code would prove more functional than mine?

Big hug mtf. Our mind set must be towards finding ways to solve the problem before looking at solution. Most times, after looking at the solutions provided by codeacademy, always feel like “i should have done that”. While most student have a fair understanding of the concept, application seems like the hurdle that need to be crossed and we must never get tired of trying. It will (surely) be very very frustrating and tiring, but we must keep pushing until we start building the confidence and able to do better at it

A post was merged into an existing topic: About list slicing

I had the same thought process as you @method1510630593. For some unknown reason though, I was hit with a syntax error here:

File “script.py”, line 2
def remove_middle(1st, start, end):
^
SyntaxError: invalid syntax

I managed to fix the issue by using text alone (first) and that allowed the code to work. My question becomes, why is 1st not being recognized here when in the double_index problem the function is defined the same way and worked without issue?

def double_index(1st, index):

is explained here:

https://realpython.com/python-variables/#variable-names

Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters ( A-Z , a-z ), digits ( 0-9 ), and the underscore character ( _ ). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.

Thanks @stetim94.

That makes sense. That left me wondering how and why the solution given was valid… Did a bit of digging, and the first character is actually a lowercase “L” which looks awfully close to a “1”. A bit deceiving, but nice lesson to really get this principle to stick.

yes, but once you know variable names can’t start with numbers, you will start reading it as the letter L (but then lowercase)

1 Like

this was the code I used to solve the question, does anyone have a better way?
def remove_middle(lst,start,end):
length_of_string = len(lst)
starting_numbers = lst[0:(start)]
ending_numbers = lst[(end+1):(length_of_string)]
lst = starting_numbers + ending_numbers
return lst