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:
Iterate over characters of a string in Python
Next article icon

Python | Merge Range Characters in List

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

Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. 

Method #1 : Using join() + List Slicing The join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality. 

Python3




# Python3 code to demonstrate
# Merge Range Characters in List
# using join() + list slicing
 
# initializing list
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing Range, i, j
i, j = 3, 7
 
# using join() + list slicing
# Merge Range Characters in List
test_list[i : j] = [''.join(test_list[i : j])]
 
# printing result
print ("The list after merging elements : " + str(test_list))
 
 
Output : 
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

  Method #2 : Using reduce() + lambda + list slicing The task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only. 

Python3




# Python code to demonstrate
# Merge Range Characters in List
# using reduce() + lambda + list slicing
 
# initializing list
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing strt, end
strt, end = 3, 7
 
# using reduce() + lambda + list slicing
# Merge Range Characters in List
test_list[strt : end] = [reduce(lambda i, j: i + j, test_list[strt : end])]
 
# printing result
print ("The list after merging elements : " + str(test_list))
 
 
Output : 
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Time Complexity: O(n*n) where n is the number of elements in the string list. The reduce() + lambda + list slicing is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list.

Method#3:Using for loop

Approach

this approach involves using a for loop to iterate over the original list and merge the characters within the specified range.

Algorithm

1. Take input the original list and the range (i, j)
2. Create a new empty list to hold the merged result
3. Iterate over the original list using a for loop and an index variable
4. If the current index is within the range (i, j), then append the current element to a temporary string variable
5. If the current index is not within the range (i, j), then append the temporary string variable to the result list and reset the temporary string variable
6. After the loop is complete, append any remaining characters in the temporary string variable to the result list
7. Return the result list

Python3




def merge_range_characters(arr, i, j):
    result = []
    temp_str = ""
    for idx, char in enumerate(arr):
        if i <= idx < j:
            temp_str += char
        else:
            if temp_str:
                result.append(temp_str)
                temp_str = ""
            result.append(char)
    if temp_str:
        result.append(temp_str)
    return result
arr= ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
i=3
j=7
print(merge_range_characters(arr, i, j))
 
 
Output
['I', 'L', 'O', 'VEGF', 'G']

Time Complexity: O(n), where n is the length of the input list.
Space Complexity: O(n), where n is the length of the input list.

Method#4: Using reduce ():

Algorithm:

  1. Create an empty list merged to store the merged characters.
  2. Create an empty string temp_str to store the characters to be merged.
  3. Loop through each character in the input list arr along with its index:

                a. If the index is between i and j (inclusive), append the character to temp_str.

                 b. If temp_str is not empty, append it to merged and append the current character to merged.

                 c. If temp_str is empty, simply append the current character to merged.

        4.If temp_str is not empty after the loop, append it to merged.

        5.Return the merged list.

Python3




from functools import reduce
 
def merge_range_characters(arr, i, j):
    merged = []
    temp_str = ""
    for idx, char in enumerate(arr):
        if i <= idx < j:
            temp_str += char
        elif temp_str:
            merged.append(temp_str)
            merged.append(char)
            temp_str = ""
        else:
            merged.append(char)
    if temp_str:
        merged.append(temp_str)
    return merged
 
arr = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
i = 3
j = 7
 
merged_list = merge_range_characters(arr, i, j)
print("The original list is : " + str(arr))
print("The list after merging elements : " + str(merged_list))
 
#This code is contributed by Jyothi pinjala
 
 
Output
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Time complexity:
The time complexity of the merge_range_characters function is O(n), where n is the length of the input list arr. This is because the function loops through each character in arr once.

Auxiliary Space:

The space complexity of the merge_range_characters function is also O(n). This is because the function creates a new list merged to store the merged characters, which can be up to the same length as arr. Additionally, the function creates a string temp_str to store the characters to be merged, which can be up to the length of the range i to j. However, since the length of the range i to j is constant, it does not affect the overall space complexity.

METHOD 5:Using a loop

APPROACH:

Using a loop to iterate over the characters in the list, and merging adjacent characters if they form a contiguous range.

ALGORITHM:

1.Initialize index i as 0
2.Iterate over the list from 0 to n-2
a. If the current element’s ASCII value is one less than the next element’s ASCII value,
then iterate over the consecutive elements until a non-consecutive element is encountered
b. Join the consecutive elements using ”.join() method and replace the original consecutive elements with the joined element
3.Increment i by 1
4.Repeat steps 2-3 until i reaches the end of the list
5.Return the modified list

Python3




lst = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
i = 0
while i < len(lst) - 1:
    if ord(lst[i]) + 1 == ord(lst[i+1]):
        j = i + 1
        while j < len(lst) - 1 and ord(lst[j]) + 1 == ord(lst[j+1]):
            j += 1
        lst[i:j+1] = [''.join(lst[i:j+1])]
    else:
        i += 1
print(lst)
 
 
Output
['I', 'L', 'O', 'V', 'E', 'G', 'FG']

Time complexity: O(n^2)
Auxiliary Space: O(1)



Next Article
Iterate over characters of a string in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Fill list characters in String
    Given String and list, construct a string with only list values filled. Input : test_str = "geeksforgeeks", fill_list = ['g', 's', 'f', k] Output : g__ksf__g__ks Explanation : All occurrences are filled in their position of g, s, f and k. Input : test_str = "geeksforgeeks", fill_list = ['g', 's'] Ou
    9 min read
  • Character Indices Mapping in String List - Python
    We are given a string list we need to map characters to their indices. For example, a = ["hello", "world"] so that output should be [[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]]. Using a nested for loopA nested for loop iterates through each
    3 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
  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Python | Merge adjacent Digit characters
    Sometimes, more than one type of data can come in python list and sometimes its undesirably tokenized and hence we require to join the digits that has been tokenized and leave the alphabets as they are. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using list comprehensi
    3 min read
  • Split String into List of characters in Python
    We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
    2 min read
  • Create List of Numbers with Given Range - Python
    The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8
    3 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 | Pair the consecutive character strings in a list
    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 + z
    5 min read
  • Create a List of Strings in Python
    Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
    3 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