Remove empty string from list

list, python, string

Solution

You can use a list comprehension to remove all elements that are `''`:

mylist = [1, 2, 3, '', 4]
mylist = [i for i in mylist if i != '']

Then you can calculate the average by taking the sum and dividing it by the number of elements in the list:

avg = sum(mylist)/len(mylist)

Floating Point Average (Assuming python 2)

Depending on your application you may want your average to be a float and not an int. If that is the case, cast one of these values to a float first:

avg = float(sum(mylist))/len(mylist)

Alternatively you can use python 3's division:

from __future__ import division
avg = sum(mylist)/len(mylist)

Problem

I just started Python classes and I'm really in need of some help. Please keep in mind that I'm new if you're answering this. I have to make a program that takes the average of all the elements in a certain list "l". That is a pretty easy function by itself; the problem is that the teacher wants us to remove any empty string present in the list before doing the average. So when I receive the list `[1,2,3,'',4]` I want the function to ignore the `''` for the average, and just take the average of the other 4/len(l). Can anyone help me with this? Maybe a cycle that keeps comparing a certain position from the list with the `''` and removes those from the list? I've tried that but it's not working.

Original source