Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Equidistant consecutive characters Strings
Next article icon

Python | Pair the consecutive character strings in a list

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes while programming, we can face a problem in which we need to perform consecutive element concatenation. This problem can occur at times of school programming or competitive programming. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using list comprehension + zip() Combination of above functionalities can be used to solve this problem. In this, we iterate the list using list comprehension and formation of pairs using zip(). 

Python3




# Python3 code to demonstrate working of
# Consecutive element pairing in list
# using list comprehension + zip()
 
# initialize list
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Consecutive element pairing in list
# using list comprehension + zip()
res = [i + j for i, j in zip(test_list, test_list[1:])]
 
# printing result
print("List after Consecutive concatenation is : " + str(res))
 
 
Output : 

The original list : [‘G’, ‘F’, ‘G’, ‘I’, ‘S’, ‘B’, ‘E’, ‘S’, ‘T’] List after Consecutive concatenation is : [‘GF’, ‘FG’, ‘GI’, ‘IS’, ‘SB’, ‘BE’, ‘ES’, ‘ST’]

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using list comprehension + zip() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

  Method #2 : Using map() + concat() The combination of these functions can also perform this task. In this traversal logic is done by map() and concat performs the task of pairing. It’s more efficient than above method. 

Python3




# Python3 code to demonstrate working of
# Consecutive element pairing in list
# using map() + concat
import operator
 
# initialize list
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Consecutive element pairing in list
# using map() + concat
res = list(map(operator.concat, test_list[:-1], test_list[1:]))
 
# printing result
print("List after Consecutive concatenation is : " + str(res))
 
 
Output : 

The original list : [‘G’, ‘F’, ‘G’, ‘I’, ‘S’, ‘B’, ‘E’, ‘S’, ‘T’] List after Consecutive concatenation is : [‘GF’, ‘FG’, ‘GI’, ‘IS’, ‘SB’, ‘BE’, ‘ES’, ‘ST’]

Method #3 : Using loop + range()

Another approach could be using a for loop and the range() function. We can iterate through the list using a for loop and use the range() function to get the index of the current element and the next element. Then we can concatenate the current element with the next element and append the result to a new list.

Python3




# Python3 code to demonstrate working of
# Consecutive element pairing in list
# using for loop and range()
   
# initialize list
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
   
# printing original list
print("The original list : " + str(test_list))
   
# Consecutive element pairing in list
# using for loop and range()
res = []
for i in range(len(test_list)-1):
    res.append(test_list[i] + test_list[i+1])
   
# printing result
print("List after Consecutive concatenation is : " + str(res))
#this code is contributed by edula vinay kumar reddy
 
 
Output
The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] List after Consecutive concatenation is : ['GF', 'FG', 'GI', 'IS', 'SB', 'BE', 'ES', 'ST']

This approach has a Time complexity of O(n) as we are iterating through the list once and space complexity of O(n) as we are creating a new list of the same size as the original list.

Method#4: Using NumPy module.

Algorithm:

  1. Import the numpy module
  2. Define a test list
  3. Use numpy’s char.add() function to concatenate consecutive elements of the list
  4. Convert the resulting numpy array back to a list
  5. Print the list

Python3




import numpy as np
# initialize list
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
   
# printing original list
print("The original list : " + str(test_list))
 
res = np.char.add(test_list[:-1], test_list[1:])
# printing result
print("List after Consecutive concatenation is : " + str(res.tolist()))
#this code contributed by tvsk.
 
 

Output:

The original list : [‘G’, ‘F’, ‘G’, ‘I’, ‘S’, ‘B’, ‘E’, ‘S’, ‘T’] List after Consecutive concatenation is : [‘GF’, ‘FG’, ‘GI’, ‘IS’, ‘SB’, ‘BE’, ‘ES’, ‘ST’]

Time complexity: O(n), where n is the length of the input list. This is because the numpy’s char.add() function iterates over the list only once.

Auxiliary space: O(n), where n is the length of the input list. This is because the numpy’s char.add() function creates a new array of size n-1 to store the concatenated elements.

Method#5:Using zip and slicing

Algorithm 

  1. Initialize the input list.
  2. Zip the original list with itself by slicing it, with second copy of list starting from second element to the end.
  3. Map each zipped tuple to the concatenated string obtained from the elements of tuple.
  4. Convert the map object to list.
  5. Print the list of consecutive element pairing in the list

Python3




# initialize list
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
   
# printing original list
print("The original list : " + str(test_list))
 
# Consecutive element pairing in list
# using zip and slicing
res = [x+y for x,y in zip(test_list, test_list[1:])]
 
# printing result
print("List after Consecutive concatenation is : " + str(res))
#This code is contributed by Vinay Pinjala.
 
 
Output
The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] List after Consecutive concatenation is : ['GF', 'FG', 'GI', 'IS', 'SB', 'BE', 'ES', 'ST']

Time Complexity:
The time complexity of this algorithm is O(n) as the list needs to be iterated only once and zip, slicing and concatenation are constant time operations.

Auxiliary Space:
The space complexity of this algorithm is O(n) as it creates a new list of tuples equal to the size of the original list. However, the list of tuples is not stored in memory and only the final list is stored, which is equal to the size of the original list minus one.



Next Article
Python - Equidistant consecutive characters Strings
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Equidistant consecutive characters Strings
    Given a Strings List, extract all the strings, whose consecutive characters are at the common difference in ASCII order. Input : test_list = ["abcd", "egil", "mpsv", "abd"] Output : ['abcd', 'mpsv'] Explanation : In mpsv, consecutive characters are at distance 3. Input : test_list = ["abcd", "egil",
    9 min read
  • Python - Strings with all given List characters
    GIven Strings List and character list, extract all strings, having all characters from character list. Input : test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"], chr_list = [ 'f', 'r', 'e'] Output : ['free', "Geeksforgeeks"] Explanation : Only "free" and "Geeksforgeeks" contains all 'f', 'r' and
    4 min read
  • Python | String List to Column Character Matrix
    Sometimes, while working with Python lists, we can have a problem in which we need to convert the string list to Character Matrix where each row is String list column. This can have possible application in data domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using
    5 min read
  • Python | Convert string List to Nested Character List
    Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehen
    7 min read
  • Python - Convert Strings to Character Matrix
    Sometimes, while dealing with String lists, we can have a problem in which we need to convert the Strings in list to separate character list. Overall converting into Matrix. This can have multiple applications in data science domain in which we deal with lots of data. Lets discuss certain ways in wh
    3 min read
  • Python | Custom Consecutive Character Pairing
    Sometimes, while working with Python Strings, we can have problem in which we need to perform the pairing of consecutive strings with deliminator. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + list comprehension T
    4 min read
  • Python program to extract characters in given range from a string list
    Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
    4 min read
  • Python | Concatenate N consecutive elements in String list
    Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let's discuss certain ways in which this task can be performed. Method #1: Using format() + zip() + i
    8 min read
  • Python - Concatenate Random characters in String List
    Given a String list, perform concatenation of random characters. Input : test_list = ["Gfg", "is", "Best", "for", "Geeks"] Output : "GiBfe" Explanation : Random elements selected, e.g G from Gfg, etc.Input : test_list = ["Gfg", "is", "Best"] Output : "fst" Explanation : Random elements selected, e.g
    6 min read
  • Python - Custom Consecutive character repetition in String
    Given a String, repeat characters consecutively by number mapped in dictionary. Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 3} Output : GGGeekkkkksss444GGGeekkkkksss Explanation : Each letter repeated as per value in dictionary.Input : test_str = 'Geeks4G
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences