5 Best Ways to Join Only Adjacent Words in a Python List

Rate this post

πŸ’‘ Problem Formulation: You have a Python list of words, and you need to join only adjacent words based on a condition or specific requirement. For instance, given the list ['apple', 'banana', 'cherry', 'date'], your task is to join the adjacent words to create a new list such as ['apple banana', 'cherry date'].

Method 1: Using a For Loop and List Slicing

This method involves iterating over the list with a regular for loop and joining pairs of words using list slicing. It is straightforward and allows for additional custom logic during the join operation.

Here’s an example:

words = ['apple', 'banana', 'cherry', 'date']
pairs = [words[i] + ' ' + words[i + 1] for i in range(0, len(words), 2)]

print(pairs)

Output:

['apple banana', 'cherry date']

This code creates a new list called pairs by taking elements in steps of two and concatenating each word with its immediate neighbor, adding a space in between. The range function is used with a step of 2 to ensure that only adjacent elements are joined.

Method 2: Using the zip Function with List Comprehension

The zip function can be used together with list comprehension to pair adjacent elements from the original list and join them with a space character.

Here’s an example:

words = ['apple', 'banana', 'cherry', 'date']
paired_words = [' '.join(pair) for pair in zip(words[::2], words[1::2])]

print(paired_words)

Output:

['apple banana', 'cherry date']

This snippet uses zip along with list comprehensions. It zips the elements of two sublist slices: one starting at index 0 and another at index 1, both progressing in steps of two. Each zipped pair is joined with a space to create the paired words.

Method 3: Using itertools and izip_longest

Using the itertools.izip_longest function allows joining adjacent words while handling lists with an odd number of elements, filling in None for any missing items.

Here’s an example:

from itertools import zip_longest

words = ['apple', 'banana', 'cherry', 'date']
paired_words = [' '.join(filter(None, pair)) for pair in zip_longest(words[::2], words[1::2])]

print(paired_words)

Output:

['apple banana', 'cherry date']

In this example, zip_longest is used to process lists that might have an odd number of elements, ensuring that no index out-of-range errors occur. filter(None, pair) is used to remove any None values resulted from missing elements in pairing.

Method 4: Using a While Loop

This approach uses a while loop to join adjacent words, providing more control over the iteration process and allowing for additional operations during the pairing.

Here’s an example:

words = ['apple', 'banana', 'cherry', 'date']
paired_words = []
i = 0
while i < len(words) - 1:
    paired_words.append(words[i] + ' ' + words[i + 1])
    i += 2

print(paired_words)

Output:

['apple banana', 'cherry date']

The code snippet declares an empty list and a counter variable, i. A while loop is used to iterate over the list indexes and adjacent elements are joined and appended to the paired_words list every two indexes.

Bonus One-Liner Method 5: Using List Comprehension with String Formatting

For a concise one-liner solution, list comprehension can be combined with string formatting to create pairs of adjacent words. It’s a compact method that maintains readability.

Here’s an example:

words = ['apple', 'banana', 'cherry', 'date']
paired_words = [f"{words[i]} {words[i+1]}" for i in range(0, len(words), 2)]

print(paired_words)

Output:

['apple banana', 'cherry date']

This one-liner uses the f-string formatting feature of Python 3.6+ to join adjacent items from the list. The range function dictates that we should consider every two elements starting from index 0.

Summary/Discussion

  • Method 1: For Loop and List Slicing. Simple to understand and implement. Less efficient on very large lists due to the use of a for loop.
  • Method 2: Using zip Function with List Comprehension. Compact and Pythonic. The zip method can be less intuitive for beginners.
  • Method 3: Using itertools and izip_longest. Robust and handles lists with an odd number of elements. Requires an additional import and has a slightly more complex syntax.
  • Method 4: Using a While Loop. Offers more control in complex scenarios. Less Pythonic and potentially slower.
  • Bonus One-Liner Method 5: Using List Comprehension with String Formatting. Very readable and concise. Requires Python 3.6 or newer for f-string usage.