alter the format of output

Viewed 41

I have the following code:

a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
d=[a,b,c]
print(d)
result=[]
for i in d:
    for j in i:
        f=j**2
        result.append(f)  
    print(result)

This is the output that i am getting:

[1, 4, 9, 16]
[1, 4, 9, 16, 25, 36, 49, 64]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]

This is the output that i want:

[1, 4, 9, 16]
[25, 36, 49, 64]
[81, 100, 121, 144]

I want to use this nested list only to get the desired output.

4 Answers

You have to do it in this way:

a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
d=[a,b,c]
print(d)
#result=[]
for i in d:
  result = []
  for j in i:
    f=j**2
    result.append(f)  
  print(result)

Your result variable has to be inside the loop to update the whole variable

You need to empty results every time you iterate through a new sublist. This way it does not keep on adding to results.

a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
d=[a,b,c]
for i in d:
    result=[]
    for j in i:
        result.append(j**2)  
    print(result)

Another option would to assign result to an empty list outside your main for loop, but use .clear().

a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
d=[a,b,c]
result = []
for i in d:
    result.clear()
    for j in i:
        result.append(j**2)  
    print(result)

Also you can use list comprehension to simplify your code.

a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
result = [[num**2 for num in l] for l in [a,b,c]]

You can use list comprehensions :

a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
d=[a,b,c]
print(d)

def fsquare(a):
    return a**2

def print_line_by_line(l):
    [print(e) for e in l]

result1=[]
for l in d:
    #use list comprehensions to apply a function on all items of a list
    f=[fsquare(element) for element in l]
    result1.append(f)  
print_line_by_line(result1)

result2=[]
#use list nested list comprehensions to apply a function on all items within nested lists
result2=[[fsquare(element) for element in l] for l in d]
print_line_by_line(result2)

print(result2)

You can also TRY:

for item in (list(map(lambda x:x**2,i)) for i in d):
    print(item)
Related