Python | Ways to join pair of elements in list
Given a list, the task is to join a pair of elements of the list. Given below are a few methods to solve the given task.
Method #1: Using zip() method
Python3
# Python code to demonstrate# how to join pair of elements of list# Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f']# Printing initial listprint ("Initial list", str(ini_list))# Pairing the elements of listsres = [i + j for i, j in zip(ini_list[::2], ini_list[1::2])]# Printing final resultprint ("Result", str(res)) |
Output:
Initial list ['a', 'b', 'c', 'd', 'e', 'f'] Result ['ab', 'cd', 'ef']
Time complexity: O(n), where n is the length of the initial list.
Auxiliary space: O(n), as the final result list (res) is created and stored in memory, with a size proportional to the input list.
Method #2: Using list comprehension and next and iters
Python3
# Python code to demonstrate# how to join pair of elements of list# Initialising listini_list = iter(['a', 'b', 'c', 'd', 'e', 'f'])# Pairing the elements of listsres = [h + next(ini_list, '') for h in ini_list]# Printing final resultprint ("Result", str(res)) |
Output:
Result ['ab', 'cd', 'ef']
Time complexity: O(n)
Auxiliary space: O(n)
Method #3: Using list comprehension
Python3
# Python code to demonstrate# how to join pair of elements of list# Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f']# Printing initial listsprint ("Initial list", str(ini_list))# Pairing the elements of listsres = [ini_list[i] + ini_list[i + 1] for i in range(0, len(ini_list), 2)]# Printing final resultprint ("Result", str(res)) |
Output:
Initial list ['a', 'b', 'c', 'd', 'e', 'f'] Result ['ab', 'cd', 'ef']
Time Complexity: O(n) where n is the number of elements in the list “ini_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list


Please Login to comment...