简体   繁体   中英

I have a list of numbers where the 1st digit is appended to a new list, then last, then 2nd, then 2nd last and so on

Following is my code:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
            print(final_list)
    except IndexError:
        pass

Now the Input I am giving is:

I/N: Enter the elements: 12345
My desired output is [1,5,2,4,3]
But the output I am actually getting is:

[1,5]
[1,5,2,4]

Can anyone please help me figure out where am I going wrong? I tried but, I cannot figure it out by myself Thanks in advance.

The print statement needs to be after the try / except clause:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
    except IndexError:
        pass
    print(final_list)

With this, we get the desired output.

I don't think this is the best solution, so here's one way of avoiding the try / except clause:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    switch = False
    while newlist:
        final_list.append(newlist.pop(-switch))
        switch = not switch
    print(final_list)

You are currently printing the list in every iteration of the loop. Be careful with the indentation.

It should be:

for x in range(len(newlist)):
    final_list.append(newlist.pop(0))
    final_list.append(newlist.pop())
print(final_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM