I’m trying to figure out how I can easily perform a math calculation on a list in Python. Lets say I have x = [1,2,3,4,5,6,7,8,9]
Lets say I want to square every single value in the array. I thought it would make sense to do something like so: x ** 2 which only seems to replicate the array two times.
I realised that I can easily do this all with NumPy, but I’d really like to do it without having to pull in the library.
I was thinking of maybe multiplying the array by itself to get the same effect, but whatever notation I use seems to either error out or multiple the array out…
you want to make square a list,
hmm I don’t know if you know about list generator, but I can make all the content of list square I use this code
x = [1,3,4,5,6,7,8]
t = [ t**2 for t in x ]
Woah, cool! That’s called a list generator?
Ok now say I have two lists such as:
a = [1,2,3,4,5,6,7,8,9]
b = [5,3,7,4,2,4,6,5,3]
Can I somehow bring in BOTH arrays and subtract a - b itemwise?
lol oh man I just realised I can do it this way:
[ a[n] - b[n] for n in range(0, len(a)) ]
Isn’t there a prettier way of doing this though?
Yes, you can do this:
[m - n for m,n in zip(a,b)]
zip() brings both lists into the loop.