I have two lists of strings that, in a better world, would be one list. I need to concatenate the lists, but the last element of the first list needs to be concatenated with the first element of the second list. So these guys:
list1 = ["bob", "sal"]
list2 = ["ly", "nigel"]
needs to become
out = ["bob", "sally", "nigel"]
So this isn’t hard, but I’m wondering why my one liner doesn’t work?
out = (list1[-1] += list2.pop(0)) += list2
Why isn’t this equivalent to
out = list1[-1]+=list2.pop(0)
out += list2
?
I have to do this a large percentage of the time through some 400K records. So if anyone has a better way to do this, then I’d be grateful!
Remove all those
+=operators, they don’t make sense here. If you want to use them as a replacement fora.extend(b), then remember, that they cannot be used as an expression. This command modifies thealist, but does not return anything. Soc = a.extend(b)gives nothing toc.Try this instead (it even does not modify original lists!):
returns what you want.
list1[:-1]is a list from list1 without the last element.list1[-1]is the last element from list1.list2[0]is the first element from list2.list1[-1] + list2[0]is a concatenated string.[ list1[-1] + list2[0] ]is a list with one element (concatenated string).list2[1:]is a list from list2 without the first element.