Home > Software design >  ordering a list through a function
ordering a list through a function

Time:05-04

Could you help see what's wrong with my code? In an exercise, I want to order a list.

def order_num(a_list):

    list = []
    for i, j in a_list:
        if i > J:
            list.append(i)
            a_list.remove(i)
        elif i == j:
            list.append(i)
            a_list.remove(i)
        else:
            list.append(j)
            a_list.remove(j)
    print(a_list)


the_list = [1, 2, 3, 4, 5]
order_num(the_list)

I get the following error:

Traceback (most recent call last):
  File "/tmp/sessions/a1c53481210f2aad/main.py", line 19, in <module>
    order_num(the_list)
  File "/tmp/sessions/a1c53481210f2aad/main.py", line 4, in order_num
    for i, j in a_list:
TypeError: cannot unpack non-iterable int object

CodePudding user response:

You are trying to take two elements of a_list when iterating over it. It does not work this way. When looping over your list, your code should look like this:

for val in a_list:

You can keep the item from the previous iteration in a variable that you can declare before the loop and initialize it to 0 (assuming this is an integer list that you are sorting in ascending order). Your code would look something like this:

previous_val = 0
for val in a_list:
   if previous_val > val:
...
   previous_val = val

I'll let you figure out the rest of your assignment :)

CodePudding user response:

First two issues:

  • Your code sample has a variable J which I presume is j
  • Your code sample has a variable a_liste which I presume is a_list

The reason your code isn't working is because you are trying to "unpack" a list. You can unpack a tuple, but to iterate through a list, you only call one variable at a time, like:

for i in a_list:
    #  do something with i

If you want to compare two items within your list, one option is to iterate a second time.

for i in a_list:
    for j in a_list:

Or you might want to think about iterating through the indices of the list using for i in range(len(a_list)): instead.

  • Related