Related Articles

Related Articles

Python | Ways to join pair of elements in list
  • Last Updated : 25 Jun, 2019

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# how to join pair of elements of list
  
# Initialising list
ini_list = ['a', 'b', 'c', 'd', 'e', 'f']
  
# Printing initial list 
print ("Initial list", str(ini_list))
  
# Pairing the elements of lists
res = [i + j for i, j in zip(ini_list[::2], ini_list[1::2])]
  
# Printing final result
print ("Result", str(res))

chevron_right


Output:

Initial list ['a', 'b', 'c', 'd', 'e', 'f']
Result ['ab', 'cd', 'ef']

 
Method #2: Using list comprehension and next and iters

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# how to join pair of elements of list
  
# Initialising list
ini_list = iter(['a', 'b', 'c', 'd', 'e', 'f'])
  
# Pairing the elements of lists
res = [h + next(ini_list, '') for h in ini_list]
  
# Printing final result
print ("Result", str(res))

chevron_right


Output:



Result ['ab', 'cd', 'ef']

 
Method #3: Using list comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# how to join pair of elements of list
  
# Initialising list
ini_list = ['a', 'b', 'c', 'd', 'e', 'f']
  
# Printing initial lists
print ("Initial list", str(ini_list))
  
# Pairing the elements of lists
res = [ini_list[i] + ini_list[i + 1
       for i in range(0, len(ini_list), 2)]
  
# Printing final result
print ("Result", str(res))

chevron_right


Output:

Initial list ['a', 'b', 'c', 'd', 'e', 'f']
Result ['ab', 'cd', 'ef']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :