0

Can this code be shorter in someway without importing any modules?

def multiply_by2(li):
    new_list = []
    for i in li:
        new_list.append(i*1)
        new_list.append(i*2)
        new_list.append(i*3)
        new_list.append(i*4)
        new_list.append(i*5)
        new_list.append(i*6)
        new_list.append(i*7)
        new_list.append(i*8)
        new_list.append(i*9)
        new_list.append(i*10)
    return new_list

print(multiply_by2([5]))

5 Answers5

0

I'm not sure if the function you made does what is intended based off its name, but it's an easy fix to make it more compact. If you just wanted to multiply everything in the list by two, you could do a similar loop through all li[i] and *= 2. Hope that answers you question, but add more detail if not.

def multiply_by2(li):
    new_list = []
    for i in li:
        for j in range(1,11):
            new_list.append(i*j)
    return new_list
delta95
  • 16
  • 4
0

You can do:

def multiply_by2(li, length=10):
    new_list = []
    for i in li: for j in range(1,length + 1): new_list.append(i * j)
    return new_list

print(multiply_by2([5]))

But we can do better, you can see that there is even a one-liner:

def multiply_by2(li, length=10): return [i * j for i in li for j in range(1,length + 1)]

print(multiply_by2([5]))
M Z
  • 4,571
  • 2
  • 13
  • 27
0

Here's one way to do it

def multiply_by2(li,range_needed):
    new_list = []
    for i in range(1,range_needed+1):
      new_list.append(li*i)
    return new_list

print(multiply_by2(5,10))

Zain Sarwar
  • 1,226
  • 8
  • 10
0

I made a code for you.

def multiply_by2(li):
    new_list = [(j+1)*i for i in li for j in range(10)]
    return new_list
Ahmed Mamdouh
  • 696
  • 5
  • 12
0
def multiply_by2(li,range_needed):
    return [li*i for i in range(1,range_needed+1)] 
vgeorge
  • 96
  • 8