Home > Enterprise >  using loops to create a new array that gets its values from a different array, starting on the secon
using loops to create a new array that gets its values from a different array, starting on the secon

Time:02-12

I am trying to make a function that creates an array from the functions original array, that starts on the second element and multiplies by the previous element. Example

input: [2,3,4,5]
output: [6,12,20]

I am trying to use a loop to get this done and here is my code so far

def funct(array1):
     newarray = []
     for x in array1[1:]:
          newarray.append(x*array1)
     return newarray

I am at a loss as I am just learning python, and i've tried various other options but with no success. Any help is appreciated

CodePudding user response:

try

A = [2, 3, 4, 5]
output = [a*b for a, b in zip(A[1:], A[:-1])]

CodePudding user response:

You can use a list comprehension like so:

inp = [2,3,4,5]
out = [j * inp[i-1] for i,j in enumerate(inp) if i != 0]

Output:

[6,12,20]
  • Related