-3
l2=[[13,11,9],[7,5,3],[1]]

I want to multiply each sublist in list l2 with a constant number i.e 13*1,11*1,9*1 and 7*2,5*2,3*2 and 1*3 and the final result would be 13,11,9 and 14,10,6 and 3.

Austin
  • 25,759
  • 4
  • 25
  • 48
  • 3
    All that has been posted is a program description. However, we need you to [ask a question](//stackoverflow.com/help/how-to-ask). We can't be sure what you want from us. Please [edit] your post to include a valid question that we can answer. Reminder: make sure you know [what is on-topic here](//stackoverflow.com/help/on-topic); **asking us to write the program for you**, suggestions, and external links are **off-topic.** – Patrick Artner Feb 11 '19 at 18:24
  • This is a more general versionof https://stackoverflow.com/questions/43671999/python-multiply-each-item-in-sublists-by-a-list .. if the list would contain the same number instead of different ones... similarly question is here https://stackoverflow.com/questions/26446338/how-to-multiply-all-integers-inside-list/26446368 and there are about a dozend more on SO already – Patrick Artner Feb 11 '19 at 18:26

6 Answers6

1

Using enumerate

Ex:

l2=[[13,11,9],[7,5,3],[1]]
print([[j*i for j in v] for i, v in enumerate(l2, 1)])

Output:

[[13, 11, 9], [14, 10, 6], [3]]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can leverage enumerate here:

l2 = [[13,11,9],[7,5,3],[1]]

l3 = [[x * (idx + 1) for x in sublist] for idx, sublist in enumerate(l2)]
print(l3)

This yields

[[13, 11, 9], [14, 10, 6], [3]]
Jan
  • 42,290
  • 8
  • 54
  • 79
0

Try this:

l2=[[13,11,9],[7,5,3],[1]]

counter = 1
for i in range(len(l2)):
    for j in range(len(l2[i])):
        l2[i][j] *= counter        
    counter += 1

print(l2)
Heyran.rs
  • 501
  • 1
  • 10
  • 20
0

Is it always the first sublist is 1, the 2nd is two, etc?

for i in range(0, len(l2)):
    i += 1
    print(f'{l2[i-1]} times {i}')
    print(list(map(lambda x: x*i, l2[i-1])))
Patrick Conwell
  • 630
  • 1
  • 5
  • 10
0

One liner with map and enumerate

[map((idx).__mul__, sublist) for idx,sublist in enumerate(l2,1)] #[[13, 11, 9], [14, 10, 6], [3]]

using numpy.multiply

import numpy as np
[np.multiply(sublist,[idx]).tolist() for idx,sublist in enumerate(l2,1)]
mad_
  • 8,121
  • 2
  • 25
  • 40
0
new_list = []
multiplier = 1 
# passing over sublists( e.g. [13,11,9] = li) in l2
for li in l2: 
    # multiply all elements in sublist(li) with multiplier(in first step multiplier = 1)
    # append the multiplied sublist to the new list
    new_list.append([li[i]*multiplier for i in range(len(li))])
    # multiplier increase by one (e.g. in second step we need to multiply elements from second sublist with multiplier = 2)
    multiplier += 1
print (new_list)
ncica
  • 7,015
  • 1
  • 15
  • 37