Reputation: 4564
I am creating a if
condition-based list. I want to create an empty list if the condition is not satisfied.
My code:
ip_list = []
op_list= [ip_list[0] if len(ip_list)>0 else '']
Present output:
op_list = ['']
Expected output:
op_list = []
Upvotes: 1
Views: 61
Reputation: 7303
You only need the first element if ip_list
has any.
Here is one of the easiest solution for that:
[ip_list[0]] if ip_list else []
Upvotes: 0
Reputation: 14423
This can be accomplished more succinctly via slicing:
op_list = ip_list[:1]
If ip_list
has at least one element, op_list
will be a singleton list with the first element of ip_list
. Otherwise, op_list
will be an empty list.
>>> a = [1, 2, 3]
>>> b = []
>>> a[:1]
[1]
>>> b[:1]
[]
Upvotes: 2