a doubt

93 views
Skip to first unread message

Nirmala.M MCA

unread,
Dec 18, 2020, 12:14:53 PM12/18/20
to Discussion forum for Programming, Data Structures&Algorithms Using Python
a=[0,1,2,3]
for a[-1] in a:
    print(a[-1])
    

can u explain this code

ARUN KUMAR

unread,
Dec 18, 2020, 12:41:18 PM12/18/20
to Discussion forum for Programming, Data Structures&Algorithms Using Python, Nirmala.M MCA
i have also same double....

16-ICS-041 Prateek

unread,
Dec 19, 2020, 6:01:51 AM12/19/20
to Discussion forum for Programming, Data Structures&Algorithms Using Python, Nirmala.M MCA
see, you are taking a[-1] instead of i,  
so in first step you are setting a[-1]=0 (as loop will iterate in "a" list so now list will become  [0,1,2,0] ) then it will print a[-1] which is "0" now.
then in next step a[-1] will be 1 ,so 0 will be replaced by 1(new list [0,1,2,1]) it will print "1"
after that  a[-1] will be 2 so 1 will be replaced by 2 (new list [0,1,2,2]) and a[-1] will be "2"
and in last step a[-1] will be 2 since last updated list was [0,1,2,2]  so new list will also remain [0,1,2,2] and a[-1] will again print "2"

output will be -> 0
                             1
                             2
                             2
hope , this will help

On Friday, December 18, 2020 at 10:44:53 PM UTC+5:30 Nirmala.M MCA wrote:
Reply all
Reply to author
Forward
0 new messages