I'm working with a list that contains both strings and integers, and I want to create a function that concatenates new elements to these strings and integers based on different conditions. For instance if the element in the list is an integer I want to add 100 to it; if the element is a string I want to add "is the name". I tried working with a list comprehension but couldn't figure out how to account for strings and integers both being present in the list (so not sure if this is possible here). Here's a basic example of what I'm working with:
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
the output would look like this:
sample_list = ['buford is the name', 101, 'henley is the name', 102, 'emi is the name', 103]
I tried using something like this:
def concat_func():
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
[element + 100 for element in sample_list if type(element) == int]
I also tried using basic for loops and wasn't sure if this was the right way to go about it instead:
def concat_func():
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
for element in sample_list:
if type(element) == str:
element + " is the name"
elif type(element) == int:
element + 100
return sample_list
You were close. instead of checking for equality with type, use 'is'. You can also do isinstance() as pointed out in the comments to check for inheritance and subclasses of str/int.
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
newlist = []
for s in sample_list:
if type(s) is int:
newlist.append(s + 100)
elif type(s) is str:
newlist.append(s + ' is the name')
else:
newlist.append(s)
newlist2 = []
for s in sample_list:
if isinstance(s, int):
newlist2.append(s + 100)
elif isinstance(s, str):
newlist2.append(s + ' is the name')
else:
newlist2.append(s)
print(newlist)
print(newlist2)