Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to write a loop

Tags:

python

loops

list

I have two lists: a = [1, 2, 3] and b = [4, 5, 6].

I have used two loops in python to subtract each element of b from each element of a.

import numpy as np
a = [1, 2, 3]
b = [4, 5, 6]
p = -1
result = np.zeros(len(a)*len(a))
for i in range(0,len(a)):
    for j in range(0,len(a)):
        p = p + 1
        result[p] = a[i] - b[j]

My result is correct: result = [-3., -4., -5., -2., -3., -4., -1., -2., -3.].

However, I would like to know if there is more elegant('pythonic') way to do it.

like image 531
DimKoim Avatar asked Sep 21 '26 18:09

DimKoim


1 Answers

There is no need to use an index. You can iterate over the values.

a = [1, 2, 3]
b = [4, 5, 6]
result = []
for x in a:
    for y in b:
        result.append(x - y)

The pythonic way would be a list comprehension.

a = [1, 2, 3]
b = [4, 5, 6]
result = [x - y for x in a for y in b]

Please bear in mind that you should use meaningful names for a, b, xand y in real code.

like image 170
Matthias Avatar answered Sep 23 '26 08:09

Matthias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!