Home > OS >  how do i create a new list M from an existing list L in python?
how do i create a new list M from an existing list L in python?

Time:08-19

the code takes user input in list L and displays only the numbers which are divisible by 5 or 7 or both in ascending order.

i need the output in the form of a list M and i don't know how to execute this. for example,

input 4 5 35 7 8 9 14 10

output [5, 7, 10, 14, 35]

but the output i get, is:- 5 7 10 14 35

how do i incorporate list M?

L=[int(i)for i in input().split()]

L.sort()

for i in L:

  if(i%5==0 and i%7==0):
    print(i)
  elif(i%5==0):
      print(i)
  elif(i%7==0):
        print(i)

CodePudding user response:

If I understand you correctly you can add results in output list and the use str.join to format it:

L = [int(i) for i in input().split()]
L.sort()

output = []
for i in L:
    if i % 5 == 0 and i % 7 == 0:
        output.append(f"{i} is divisible by 5 and 7")
    elif i % 5 == 0:
        output.append(f"{i} is divisible by 5")
    elif i % 7 == 0:
        output.append(f"{i} is divisible by 7")
    else:
        output.append(f"{i} is not divisible by 5 or 7")

print(", ".join(output))

Prints (for example):

5 6 7 35
5 is divisible by 5, 6 is not divisible by 5 or 7, 7 is divisible by 7, 35 is divisible by 5 and 7

EDIT:

L = [int(i) for i in input().split()]
L.sort()

output = []
for i in L:
    if i % 5 == 0 or i % 7 == 0:
        output.append(i)

print(output)

Prints:

4 5 35 7 8 9 14 10
[5, 7, 10, 14, 35]
  • Related