akram.bridge akram.bridge - 27 days ago 4
Python Question

Creating a new list using for loop?

I need to write a function that normalizes a vector (finds the unit vector). A vector can be normalized by dividing each individual component of the vector by its magnitude.

The input for this function will be a vector i.e. 1 dimensional list containing 3 integers.

The code follows:

def my_norml(my_list):
tot_sum = 0
for item in my_list:
tot_sum = tot_sum + item**2
magng = tot_sum**(1/2)
norml1 = my_list[0]/magng #here i want to use a for loop
norml2 = my_list[1]/magng
norml3 = my_list[2]/magng
return [norml1, norml2,norml3]

Answer

There's a couple of things you could do here.

Initially, let me just point out that tot_sum = tot_sum + item**2 can be written more concisely as tot_sum += item**2. To answer your question, you could use a loop to achieve what you want with:

ret_list = []
for i in my_list:
    ret_list.append(i / magng)
return ret_list

But this isn't the best approach. It is way better to utilize comprehensions to achieve what you need; also, the sum built-in function can do summing for you instead of you needing to manually perform it with a for-loop:

magng can easily be computed in one line by passing a comprehension to sum. With the comprehension you raise each item to ** 2 and then immediately divide the summation that sum returns:

magng = sum(item**2 for item in my_list) ** (1/2)

After this, you can create your new list by again utilizing a comprehension:

return [item/magng for item in my_list]

Which creates a list out of every item in my_list after dividing it by magng.

Finally, your full function could be reduced to two lines (and one but that would hamper readability):

def my_norml(my_list):
    magng = sum(item**2 for item in my_list) ** (1/2)
    return [item/magng for item in my_list]

This is more concise and idiomatic and pretty intuitive too after you've learned comprehensions.