Python Forum

Full Version: List in Python 3.8
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a novice python programmer. I was learning and practicing the List data structure in python 3.8. To place my certain query I will take help from the following example.
For example, a list named Numbers has been created below.

Numbers=[5,6,3,4,8,9,2,1,7]    #Defined a list.

print(Numbers[0])              #Output of this statement 5 is understood. 
print(Numbers[8])              #Output of this statement 7 is understood.

#print(Numbers[9])             This would show IndexError: list index out of range and it is logical and understood.

print(Numbers[0:8])            #Output of this statement [5,6,3,4,8,9,2,1] is understood as it is mentioned that it works like this.
print(Numbers[0:9])            #Output of this statement [5,6,3,4,8,9,2,1,7] is surprisingly worked and understood!

print(Numbers[-9])             #Output of this statement 5 is understood.
print(Numbers[-9:-1])          #Output of this statement [5,6,3,4,8,9,2,1] is understood as it is mentioned that it works like this.

print(Numbers[-9:0])           #Output of this statement [] instead of [5,6,3,4,8,9,2,1,7] is surprisingly not worked and didn't understand!
                               # Or
print(Numbers[-9:-0])          #Output of this statement [] instead of [5,6,3,4,8,9,2,1,7] is surprisingly not worked and didn't understand!
My query is in the comments of the code of my given example. If anyone expert can help me to clarify this I would be grateful! Thank you.

Anwarul Kabir
>>> print(Numbers[0])
5
>>> print(Numbers[0:1])
[5]
>>> print(Numbers[0:0]) #Prints nothing since end index is not included
[]
>>> print(Numbers[-9:0]) #-9 and 0 is index for first element 5. Same like above
[]
>>> print(Numbers[-9:-0])#Negative zero is equal to normal zero
[]
Thank you for your reply. I have a complementary question in this regard. Therefore we can conclude that there is no way to show all the list items using a negative index, right?
(Apr-28-2020, 08:07 AM)AnwarulKabir Wrote: [ -> ]there is no way to show all the list items using a negative index, right
no, that is not correct. you can
>>> Numbers=[5,6,3,4,8,9,2,1,7]
>>> Numbers[::-1]
[7, 1, 2, 9, 8, 4, 3, 6, 5]
>>> Numbers[-1::-1]
[7, 1, 2, 9, 8, 4, 3, 6, 5]