Given I have the function subs() that aims to replace the value 13 with the boolean expression True. A desirable outcome would be:
list = [1, True, 'a', True, 9.0]
Upon running my code however, I come across the issue that only a true is being computed.
#Question 1
def subs(list):
results=[]
for values in list:
if values==13:
new_list = True
results.append(new_list)
return results
list = [1, 13, 'a', 13, 9.0]
subs(list)
CodePudding user response:
You are only returning the results for that loop.
Change it to this. Move the indent out of the for loop so it returns the main results outside that loop.
You also need to have an else situation where you return the original value of you do nothing.
#Question 1
def subs(list):
results=[]
for values in list:
if values==13:
results.append(True) #you can merge newlist here and remove the above line to add True directly
else:
results.append(values) #this will add the original values
return results #this will return the final list
When I run,
list = [1, 13, 'a', 13, 9.0]
subs(list)
My output is,
[1, True, 'a', True, 9.0]
CodePudding user response:
This will create a copy your initial list, if you use the commented out line instead it will also modify your original list.
def sub(array):
results = []
for index, value in enumerate(array):
if value == 13:
results.append(True)
#array[index]=True
else:
results.append(value)
return results
More pyhthonic you can shorten this to a list comprehension
sublist = [v if v!=13 else True for v in list]
CodePudding user response:
You can do this with a simple list comprehension as follows:
_list = [1, 13, 'a', 13, 9.0]
def subs(lst):
return [True if e == 13 else e for e in lst]
print(subs(_list))
Output:
[1, True, 'a', True, 9.0]
CodePudding user response:
You are returning as soon as you find a suitable value in your code, hence the output of the function subs
will always be [True]
You can simplify your code to something like this
def subs(list_):
result=[]
for value in list_:
if value==13:
result.append(True)
else:
result.append(value)
return results
Notice that if the value from the list is not 13
, then we append it to the result as is.
I also changed the naming convention, since value
only contains one value, and list
to list_
, since list
is already a declared keyword, that you should not use as a variable name.
Note that you don't have to write a for loop, but could write this code using list comprehensions like this:
def subs(list_):
return [value if value != 13 else True for value in list_]