Joining elements in list of Strings in loop with a condition

Viewed 166

Every 2 elements should be joined in a loop till the end of the list This is what i have been trying to do

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for i in range(len(items)+1):
  items[i]=items[i]+items[i+1]
  i=i+2
print(items)

Expected Output: ['ab' , 'cd' , 'ef' , 'gh' , 'ij']

5 Answers

You can supply another argument to range to specify the increment ("step"):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
res = []
for i in range(0, len(items), 2):
    res.append(items[i] + items[i + 1])
print(res)
# ['ab', 'cd', 'ef', 'gh', 'ij']

Or, better yet, use a list comprehension instead:

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
items = [items[i] + items[i + 1] for i in range(0, len(items), 2)]
print(items)
# ['ab', 'cd', 'ef', 'gh', 'ij']

you can do it using list comprehension like this:

items = [items[i] + items[i+1] for i in range(0, len(items), 2)]

A solution with regex:

>>> import re
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> re.findall('.{1,2}', ''.join(items))
['ab', 'cd', 'ef', 'gh', 'ij']

Your thought process is correct, I would double check your print statement. You are printing items, but are updating items[i] to items[i] + items[i+1]. I believe you want to print the variable you are updating.

First of all, you need to know that len() returns the number of item, not the size of the array (remember that the array index starts at 0). Here, if you want, you can look at the docs for the len() function.

Next, just to inform you, you can use the method append() to insert an object into the final position of the array. Here you can find some info on arrays.

Moreover, I want to add that in python, when using range, you can take advantage of the step value that you can pass to range: range(start, stop, step). You can read more about it here.

Said so, I would do something as follow:

output=[]
for i in range(0, len(items), 2):
    output.append(items[i]+items[i+1]);
print(output)
Related