-1

Let's say I have the following code

arr = ["a", "b", "c", "d"...]

I don't know how many items there may be, but I know it'll be a multiple of two. How would I go about appending every pair of items together, leaving me with

arr = ["ab", "cd"...]?

Hugh
  • 23
  • 2
  • 1
    Check out the `pairwise` [recipe](https://docs.python.org/2/library/itertools.html#recipes). – Mureinik Dec 23 '17 at 17:23
  • 1
    Possible duplicate of [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks), [Iterating over every two elements in a list](https://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list/), [Pairwise traversal of a list](https://stackoverflow.com/questions/3849625/pairwise-traversal-of-a-list-or-tuple/3849706#3849706) – jscs Dec 23 '17 at 17:25
  • One more way: `arr = [arr[a]+arr[b] for a,b in zip(range(0,len(arr),2),range(1,len(arr),2))]` – tonypdmtr Dec 23 '17 at 18:32

4 Answers4

1

You can try this:

arr = ["a", "b", "c", "d"]
new_data = [''.join([arr[i], arr[i+1]]) for i in range(0, len(arr), 2)]

Output:

['ab', 'cd']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Thanks, that looks like it'd work. I already have an answer that works fine, but thank you for the help. Upvoted – Hugh Dec 23 '17 at 17:26
  • 1
    You have a gold badge, so if you see a question that appears to be a blatant duplicate, I urge you to find a suitable target and close it. With great power comes great responsibility, so use it wisely. Good luck. – cs95 Dec 23 '17 at 17:37
1

Another way would be using the zip clustering idiom

def pairs(it):
    return [''.join(x) for x in zip(*[iter(it)]*2)]
cs95
  • 379,657
  • 97
  • 704
  • 746
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 1
    Very nice use of `iter`. However, did you mean `iter(iterable)` rather than `iter(it)`? – Ajax1234 Dec 23 '17 at 17:37
  • 1
    I'd recommend `i = iter(it)` and then `zip(i, i)`, it's a lot cleaner. Well done though, I like your answer. – cs95 Dec 23 '17 at 17:42
0

I've got an answer. I did

u = []
for x in range(len(arr)):
    if x % 2 == 0:
        u.append(arr[x] + arr[x + 1])
print u
Hugh
  • 23
  • 2
-1
 result = []
 for i range(len(arr)/2)
     result.append(arr[2*i]+arr[2*i+1])
 print result
qxang
  • 318
  • 3
  • 10