How to convert only numbers in a mixed list into float

You could create a simple utility function that either converts the given value to a float if possible, or returns it as is: def maybe_float(s): try: return float(s) except (ValueError, TypeError): return s orig_list = [‘data’, ’18’, ’17’, ‘0’] the_list = [maybe_float(v) for v in orig_list] And please don’t use names of builtin functions and … Read more

list comprehension with multiple conditions (python)

There are two distinct but similar-looking syntaxes involved here, conditional expressions and list comprehension filter clauses. A conditional expression is of the form x if y else z. This syntax isn’t related to list comprehensions. If you want to conditionally include one thing or a different thing in a list comprehension, this is what you … Read more