Mainland
Mainland

Reputation: 4564

Python Produce empty list if condition not satisafied

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

Answers (3)

Tâmer Cuba
Tâmer Cuba

Reputation: 2821

op_list = [] if ip_list else [ip_list[0]]

Upvotes: 1

Nouman
Nouman

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

Brian61354270
Brian61354270

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

Related Questions