Reputation: 93
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.
Upvotes: 1
Views: 40
Reputation: 2981
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)
Upvotes: 2
Reputation: 738
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)
Upvotes: 1