adam adam - 26 days ago 7
Python Question

how to move one element from a list to another in python

def ListNum(x):
list1 = []
for i in (x):
if x[i] < x [i + 1]:
list1.append[i]
else:
break
return(list1)
ListNum([1,2,3,4,5,6,2,3,4])


So, I input a list of numbers and go through the list and check if the first value in that list is less than the second value if so add it to
list1
, carry on until the value is greater than the next value.

So, if I input
ListNum([1,2,3,4,5,6,2,3,4])


i should get
list1[1,2,3,4,5]


but its not working

Answer

I assume that you never want to add the last item in x to list1 because there isn't an item after it to compare it with.

Your code doesn't work properly because for i in (x): iterates over the items in x, not their indices. But even if it did iterate over the indices your code could crash with an IndexError because it could attempt to compare the last item in the list with the item after it, which doesn't exist

Here are several ways to do this.

from itertools import takewhile

def list_nums0(x):
    list1 = []
    for i in range(len(x) - 1):
        if x[i] < x[i + 1]:
            list1.append(x[i])
        else:
            break
    return list1

def list_nums1(x):
    list1 = []
    for u, v in zip(x, x[1:]):
        if u < v:
            list1.append(u)
        else:
            break
    return list1

def list_nums2(x):
    list1 = []
    for i, u in enumerate(x, 1):
        if u < x[i]:
            list1.append(u)
        else:
            break
    return list1

def list_nums3(x):
    return [t[0] for t in takewhile((lambda a:a[0] < a[1]), zip(x, x[1:]))]

list_nums = list_nums3
print(list_nums([1,2,3,4,5,6,2,3,4]))

output

[1, 2, 3, 4, 5]

list_nums0 simply iterates over the indices of x.

list_nums1 uses zip to iterate in parallel over x and x[1:]. This puts the current & next items into u and v.

list_nums2 uses enumerate to get the current item in u and the index of the next item in i.

list_nums3 uses takewhile to iterate over the tuples yielded by zip until we get a pair of items that don't satisfy the test. It performs the whole operation in a list comprehension, which is slightly more efficient that using .append in a traditional for loop.

Comments