Skip to content Skip to sidebar Skip to footer

Im Trying To Transfer The Elements In The List To Another List. And Im Asking How Many Numbers Would Be Transferred To The List B But Error Is Showing

im trying to transfer element from list a to list b and im asking how many numbers would i like to transfer.It shows me this error: '<=' not supported between instances of 'Non

Solution 1:

b.append(i) returns None. therefore the comparison b.append(i) <= 2 raises an error. if you wanted to base your code on the length of the list you could use len(b). something like:

for i in a:
    if len(b) < transfer:
        b.append(i)
    else:
        break

alternatively you could do this:

b = a[:transfer]

this would just use the slice of the old list a as the new list b.

Solution 2:

  1. First of all you should prevent error when you convert input to int. There are 2 ways how to do this.

    1. Try .. except statement.

      transfer = -1while transfer < 0:
          try:
              inp = input("how many numbers would you like to transfer:?")
              transfer = int(inp)
          except:
              print("Invalid input.")
      
    2. isdecimal().

      transfer = -1while transfer < 0:
          inp = input("how many numbers would you like to transfer:?")
          if inp.isdecimal():
              transfer = int(inp)
          else:
              print("Invalid input.")
      
  2. Now about main task. There's 3 methods how to solve it.

    1. For loop using enumerate().

      for i, el in enumerate(a):
          if i < transfer:
              b.append(el)
          else:
              break
      
    2. List comprehension:

      b = [el for i, el in enumerate(a) if i < transfer]       
      
    3. List slicing:

      b = a[:transfer]
      

Post a Comment for "Im Trying To Transfer The Elements In The List To Another List. And Im Asking How Many Numbers Would Be Transferred To The List B But Error Is Showing"