Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List in Python 3.8
#1
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
Reply
#2
>>> 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
[]
Reply
#3
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?
Reply
#4
(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]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020