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:
How to Split Lists in Python?
Next article icon

Python | Shift sublist in list

Last Updated : 01 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with list, we can have a problem in which we need to shift some sublist to the desired index in the same sublist. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using insert() + pop() + loop

The combination of above functions can be used to perform a particular task. The pop function can be used to remove the sublist and insert function inserts the sublist. This happens for each element in a single iteration in a loop.

Python3




# Python3 code to demonstrate working of
# Shift sublist in list
# Using insert() + pop() + loop
 
# function to perform the task
 
 
def shift_sublist(test_list, strt_idx, no_ele, shft_idx):
    for ele in range(no_ele):
        test_list.insert(shft_idx + 1, test_list.pop(strt_idx))
    return test_list
 
 
# initializing list
test_list = [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using insert() + pop() + loop
# Shift sublist in list
res = shift_sublist(test_list, 2, 3, 6)
 
# Printing result
print("The list after shift of sublist : " + str(res))
 
 
Output : 

The original list is : [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16] The list after shift of sublist : [4, 5, 8, 10, 1, 6, 7, 3, 12, 15, 16]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.  
Auxiliary Space: O(n), where n is the number of elements in the new res list 

Method #2: Using list slicing 

This task can also be done using a list slicing technique in which one can just add the different sections of list at the required positions. 

Python3




# Python3 code to demonstrate working of
# Shift sublist in list
# Using list slicing
 
# function to perform the task
def shift_sublist(test_list, strt_idx, no_ele, shft_idx):
    return (test_list[:strt_idx] + test_list[strt_idx + no_ele : no_ele + shft_idx - 1]
            + test_list[strt_idx : strt_idx + no_ele] + test_list[shft_idx + no_ele -1:])
 
# initializing list
test_list = [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using list slicing
# Shift sublist in list
res = shift_sublist(test_list, 2, 3, 6)
 
# Printing result
print("The list after shift of sublist : " + str(res))
 
 
Output : 
The original list is : [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16] The list after shift of sublist : [4, 5, 8, 10, 1, 6, 7, 3, 12, 15, 16]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. Using list slicing performs n number of operations.
Auxiliary Space: O(n), where n is the length of the list.

Method #3: Using list comprehension and slicing

In this method, extract the sublist to be shifted using list slicing, create a new list by iterating through the original list and excluding the indices of the sublist, and insert the shifted sublist at the desired index using slicing.

Python3




def shift_sublist(test_list, strt_idx, no_ele, shft_idx):
    # Extract sublist to be shifted using list slicing and reverse it
    shifted_sublist = test_list[strt_idx:strt_idx+no_ele][::-1]
    # Create a new list by excluding indices of the sublist
    shifted_list = [test_list[i] for i in range(len(test_list)) if i not in range(strt_idx, strt_idx+no_ele)]
    # Insert the shifted sublist at the desired index using slicing
    shifted_list[shft_idx:no_ele+shft_idx] = shifted_sublist
    return shifted_list
 
# initializing list
test_list = [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
 
# printing original list
print("The original list is:", test_list)
 
# Using list comprehension and slicing
# Shift sublist in list
res = shift_sublist(test_list, 2, 3, 6)
 
# Printing result
print("The list after shift of sublist:", res)
 
 
Output
The original list is: [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16] The list after shift of sublist: [4, 5, 8, 10, 1, 12, 3, 7, 6]

Time complexity: O(n), where n is the length of the original list. This is because we only need to iterate through the original list once to extract the shifted sublist and create a new list.
Auxiliary space: O(n), as we create a new list to hold the shifted sublist and a new list to hold the remaining elements of the original list.

Method #4: Using reduce():

  1. Initialize the result as the original list.
  2. For each shift in the list of shifts:
    a. Call shift_sublist function on the result, passing in the current shift.
    b. Update the result with the returned value from shift_sublist.
  3. Return the final result.

Python3




from functools import reduce
 
def shift_sublist(test_list, strt_idx, no_ele, shft_idx):
    return (test_list[:strt_idx] + test_list[strt_idx + no_ele : no_ele + shft_idx - 1]
            + test_list[strt_idx : strt_idx + no_ele] + test_list[shft_idx + no_ele - 1:])
 
def shift_sublists(test_list, shifts):
    return reduce(lambda res, shift: shift_sublist(res, *shift), shifts, test_list)
 
test_list = [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
shifts = [(2, 3, 6), (5, 2, 9), (1, 4, 8)]
result = shift_sublists(test_list, shifts)
 
print("The original list is : " + str(test_list))
print("The list after shift of sublists : " + str(result))
#This code is contributed by Jyothi pinjala.
 
 
Output
The original list is : [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16] The list after shift of sublists : [4, 3, 12, 15, 6, 7, 16, 5, 8, 10, 1]

Time complexity: O(n), where n is the length of the input list. The shift_sublists() function applies shift_sublist() function to each tuple in shifts cumulatively using the reduce() function. Therefore, the time complexity of shift_sublists() function is O(mn), where m is the number of tuples in shifts.
Auxiliary space: O(n), where n is the length of the input list. The shift_sublists() function applies shift_sublist() function to each tuple in shifts cumulatively using the reduce() function. Therefore, the space complexity of shift_sublists() function is also O(n).



Next Article
How to Split Lists in Python?
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Check for Sublist in List-Python
    The task of checking for a sublist in a list in Python involves determining whether a given sequence of elements (sublist) appears consecutively within a larger list. This is a common problem in programming, particularly in data processing and pattern matching. For example, if we have a list [5, 6,
    4 min read
  • Python - Rear shift K in List
    The conventional problem involving the element shifts has been discussed many times earlier, but sometimes we have strict constraints to performing them and knowledge of any possible variation helps. This article talks about one such problem of shifting K’s at end of list, catch here is it checks fo
    5 min read
  • List of strings in Python
    A list of strings in Python stores multiple strings together. In this article, we’ll explore how to create, modify and work with lists of strings using simple examples. Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings. [GFGTABS
    2 min read
  • How to Split Lists in Python?
    Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
    3 min read
  • Sort Tuple of Lists in Python
    The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
    3 min read
  • Python | Shift zeroes at end of list
    The conventional problem involving the element shifts has been discussed many times earlier, but sometimes we have strict constraints performing them and knowledge of any possible variation helps. This article talks about one such problem of shifting 0's at end of list, catch here is it checks for j
    7 min read
  • Python | Indexing a sublist
    In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let's discuss certain ways in which this can be performed. Method #1 : Using index() + list co
    3 min read
  • Python | Split a list into sublists of given lengths
    The problem of splitting a list into sublists is quite generic but to split in sublist of given length is not so common. Given a list of lists and list of length, the task is to split the list into sublists of given length. Example: Input : Input = [1, 2, 3, 4, 5, 6, 7] length_to_split = [2, 1, 3, 1
    2 min read
  • Shift from Front to Rear in List - Python
    The task of shifting the first element to the rear in a list in Python involves moving the first element of the list to the end while maintaining the order of the remaining elements. For example, given the list a = [1, 4, 5, 6, 7, 8, 9, 12], the goal is to produce [4, 5, 6, 7, 8, 9, 12, 1]. Using co
    3 min read
  • How To Slice A List Of Tuples In Python?
    In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
    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