I have a following problem. I would like to form a list a conditionally.
Lets say I have a variable add_string and if it's True then
a = ["a","b","Added String","c"]
Else
a = ["a","b","c"]
what's the best way to do that? I can do that in the following manner
a = ["a","b","c"]
if add_string:
a.insert(2,"Added String")
But that's not ideal since list a might change in future and I will have to change the index in the insert function. Also I have a condition — this added string should always follow after "b". Another solution is to search for "b" in the list and then insert after that, but that adds complexity and it's ugly.
Ideally I thought it should be something like
a = ["a","b",if add_string then "Added String","c"]
-
4This sounds like an XY problem. What are you trying to do that you think warrants this approach?Code-Apprentice– Code-Apprentice2020年01月23日 23:23:18 +00:00Commented Jan 23, 2020 at 23:23
-
it's exactly what I'm trying to achieve. Of course the list names and values are different. But basically I'm trying to form a list of objects in the function X. And this function is called from another function Y. One of the arguments that's passed is that object that I have to add to the list. Sometimes this objects is passed and sometimes not. Currently I'm doing it using insert. So I'm wondering if I can do it somehow else.Roman_T– Roman_T2020年01月23日 23:31:32 +00:00Commented Jan 23, 2020 at 23:31
3 Answers 3
a = ["a","b"] + (["Added String"] if add_string else []) + ["c"]
Comments
If you know all the values when you create a, you could do something like this:
add_string = True
a = ['a', 'b'] + (['Added String'] if add_string else []) + ['c']
Output:
['a', 'b', 'Added String', 'c']
If you don't know the values in a, you could use index to find the location of 'b' in a, and insert the string after that:
a = ["a","b","c"]
add_string = True
if add_string:
a.insert(a.index("b")+1,"Added String")
print(a)
Output:
['a', 'b', 'Added String', 'c']
4 Comments
a when you create the list?You could set unwanted values to a known value (such as None) and then remove them using list comprehension:
add_string = False # Could be True
unfiltered_list = ["a","b","Added String" if add_string else None,"c"]
a = [x for x in unfiltered_list if x is not None]
print(a)