0
name = list('ayushgupta')
>>> name
['a', 'y', 'u', 's', 'h', 'g', 'u', 'p', 't', 'a']
>>> name[5:5] = list('THE')
>>> name
['a', 'y', 'u', 's', 'h', 'T', 'H', 'E', 'g', 'u', 'p', 't', 'a']
>>> name[5:5] = []
>>> name
['a', 'y', 'u', 's', 'h', 'T', 'H', 'E', 'g', 'u', 'p', 't', 'a']

If I try to delete 'T', 'H', 'E' from name using name[5:5], it doesn't work. I know I can use name[5:8] to delete the same. Could anyone explain why this is so?

3 Answers 3

1

You can change both the content and the length of a list by assigning to slice of the list. However, your slice is name[5:5]. Remember that a slice does not include the ending index. Thus, your slice starts at name[5] and continues to but does not include name[5]. In other words, your slice is empty.

In short, you are trying to delete a part of the list that already is empty. If you try an actual slice, such as name[5:8], you will be more successful. To delete just one item, try name[5:6]. The length of slice name[a:b] is b-a (if b is greater than or equal to a), which is easy to remember.

Sign up to request clarification or add additional context in comments.

Comments

0

See:

    name[5:5]

means: element from the index 5 (inclusive) to 5 (exclusive)

So you have use something as

    name[4:5]

to select (by rather complicated way) element name[4].

Comments

0

You have to do:

>>> name[5:8] = []
>>> name
['a', 'y', 'u', 's', 'h', 'g', 'u', 'p', 't', 'a']

When you did, name[5:5]=list('THE'), THE got inserted into the list from 5th index to 5th index of list. When you are doing name[5:5] = [], you are not deleting anything, instead trying to insert empty list, and hence no change. For updating the items from list from 5 to 8 index, you have to do name[5:8] = []

OR, you may use del to delete content for the list as:

>>> del name[5:8]
>>> name
['a', 'y', 'u', 's', 'h', 'g', 'u', 'p', 't', 'a']

4 Comments

"Could anyone explain why is it so?". Well?
@AndrasDeak Was already on the way to update that, Check edit :)
Good. You should consider taking your time to give a full answer for first try. It can spare you some downvotes. I'm only telling you this because I've seen you show FGITW behaviour a lot, and I don't think this benefits the askers, nor the site. If you give an answer, make it good. You'll even get more rep like that in the long run.
@AndrasDeak: I will follow your suggestion. Thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.