tags:

views:

116

answers:

5

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!

+10  A: 

Remove all those += operators, they don't make sense here. If you want to use them as a replacement for a.extend(b), then remember, that they cannot be used as an expression. This command modifies the a list, but does not return anything. So c = a.extend(b) gives nothing to c.

Try this instead (it even does not modify original lists!):

out = list1[:-1] + [ list1[-1] + list2[0] ] + list2[1:]

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.
eumiro
A: 

If you want a one-liner, here's what I'd do:

(','.join(list1)+','.join(list2)).split(',')
Chris Fonnesbeck
Doesn't work correctly if you have commas anywhere in the strings within the lists.
eumiro
+3  A: 

Assignments in Python are not operators that can be used within expressions. They are statement-level syntax.

Ned Batchelder
A: 

Apart of @eumiros answer, on what is happening there, you can acomplish what you want in a single statement with:

out = list1[:-1] + [list1[-1] + list2[0]] + list2[1:]

"There should be one-- and preferably only one --obvious way to do it."

jsbueno
A: 

I would not normally leave broken pieces of data around but would fix in place:

>>> list1 = ["bob", "sal"]
>>> list2 = ["ly", "nigel"]
>>> fix = [list1.pop()+list2.pop(0)]
>>> list1
['bob']
>>> fix
['sally']
>>> list2
['nigel']
>>> fixed = list1 + fix + list2
>>> fixed
['bob', 'sally', 'nigel']

Same time getting rid of those obvious list1 and list2 variable names with something readable.

Tony Veijalainen