I'm trying to write a function that takes 2 list variables ie first_names
and last_names
.
I'm using a nested for loop in my function to iterate through both lists and append the values to return a new 'combined' variable list.
The function takes the two list parameters but iterates through just the first index value [0] of each list and outputs that - the loop ends.
first_names = ["Dave", "James", "Steve"]
last_names = ["Smith", "Jones", "Jackson"]
def NameCombine(first_names,last_names):
combined = []
for first in first_names:
for last in last_names:
combined.append(first+last)
return combined
print(NameCombine(first_names,last_names))
Expected output: DaveSmith, JamesJones, SteveJackson
Actual output: DaveSmith
I'm expecting a new combined list of both the first and last name at each index.
But it's returning the first two values of each list and then the loop ends.
You can combine them with zip
within comprehension:
def NameCombine(first_names,last_names):
return [a+b for a, b in zip(first_names, last_names)]
You may try with this code.
first_names = ["Dave", "James", "Steve"]
last_names = ["Smith", "Jones", "Jackson"]
def NameCombine(first_names, last_names):
combined = []
for i in range(0, len(first_names)):
if last_names[i] != None:
combined.append(first_names[i] + " " + last_names[i])
else:
combined.append(first_names[i])
return combined
print(NameCombine(first_names,last_names))
The pythonic and list comprehension is my preferred way. But if you really wanted a solution using a nested loop, this would work for you. Just used your code and added an additional condition to only print the desired result.
The results from this solution are: ['DaveSmith', 'JamesJones', 'SteveJackson']
first_names = ["Dave", "James", "Steve"]
last_names = ["Smith", "Jones", "Jackson"]
def NameCombine(first_names,last_names):
combined = []
for first in first_names:
for last in last_names:
if first_names.index(first) == last_names.index(last):
combined.append(first+last)
return combined
print(NameCombine(first_names,last_names))
Since most of them here answer specifically to your question. I would like to add the other way of achieving the solution to this problem as below,
here I used map
and add
from operator module
list(map(operator.add, first_names, last_names))
# ['DaveSmith', 'JamesJones', 'SteveJackson']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.