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 Slice A List Of Tuples In Python?
Next article icon

Python Program to Split a List into Two Halves

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Splitting a list into two halves is a common operation that can be useful in many cases, such as when dealing with large datasets or when performing specific algorithms (e.g., merge sort). In this article, we will discuss some of the most common methods for splitting a list into two halves.

Using List Slicing

List slicing is a highly efficient way to split a list into two halves. By using the slicing technique, we can directly access the first and second halves of the list. This method does not modify the original list, and it preserves the order of elements.

Python
a = [1, 2, 3, 4, 5, 6]  # Integer division to find the middle index mid = len(a) // 2  # Elements from the start to the middle x = a[:mid]  # Elements from the middle to the end y= a[mid:]  print(x) print(y) 

Output
[1, 2, 3] [4, 5, 6] 

Explanation:

  • a[:mid] extracts the first half of the list, from index 0 to mid-1.
  • a[mid:] extracts the second half of the list, from index mid to the end of the list.
  • The list is split efficiently in a single step.

Let's see some more methods and see how we can split a list into two halves.

Table of Content

  • Using List Comprehension
  • Using a Loop
  • Using numpy.array_split()

Using List Comprehension

List comprehension can also be used to extract the first half and second half based on index ranges, especially if we need to apply some conditions or transformations while splitting.

Python
a = [1, 2, 3, 4, 5, 6]  mid = len(a) // 2  # Create the first half using a list comprehension x = [a[i] for i in range(mid)]  # Create the second half using a list comprehension y = [a[i] for i in range(mid, len(a))]  print(x) print(y) 

Output
First Half: [1, 2, 3] Second Half: [4, 5, 6] 

Explanation:

  • [a[i] for i in range(mid)] is used to extract the first half of the list. It loops through the list from index 0 to mid - 1 and appends those elements to the new list first_half.
  • Similarly, [a[i] for i in range(mid, len(a))] extracts the second half of the list by iterating from index mid to the end of the list and appending those elements to second_half.

Using a Loop

This method involves using a for loop to manually split the list into two parts. It can be useful if we want more control over how the list is split.

Python
a = [1, 2, 3, 4, 5, 6] mid = len(a) // 2  # Initialize empty lists to hold the two halves x = [] y = []  # Populate the first half using a loop for i in range(mid):     x.append(a[i])  # Populate the second half using a loop for i in range(mid, len(a)):     y.append(a[i])  print(x) print(y) 

Output
[1, 2, 3] [4, 5, 6] 

Explanation:

  • The loop iterates over the first half of the list and adds each element to first_half.
  • A second loop iterates over the second part of the list and adds each element to second_half.

Using numpy.array_split()

For working with numeric data or using the numpy library, numpy.array_split() provides a clean way to split lists (or arrays) into two or more parts. This function automatically handles splitting the list and is efficient for large datasets.

Python
import numpy as np  a = [1, 2, 3, 4, 5, 6]  # Creates two sub-arrays, dividing the list evenly split_lst = np.array_split(a, 2)  # Assign the first half to x x = split_lst[0]  # Assign the second half to y y = split_lst[1]  print(x) print(y) 

Output
[1 2 3] [4 5 6] 

Explanation:

  • np.array_split(a, 2) splits the list 'a' into two parts and returns them as a list of numpy arrays.
  • It also works with lists that cannot be evenly divided, automatically adjusting the size of the parts

Next Article
How To Slice A List Of Tuples In Python?

A

abhaystriver
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python Program to Swap Two Elements in a List
    In this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Swapping elements at index 0 and 4 # using multiple assignment a[0], a[4] = a[4], a[0] print(a) [/GF
    2 min read
  • Python program to insert an element into sorted list
    Inserting an element into a sorted list while maintaining the order is a common task in Python. It can be efficiently performed using built-in methods or custom logic. In this article, we will explore different approaches to achieve this. Using bisect.insort bisect module provides the insort functio
    2 min read
  • Python Program to Split the Even and Odd elements into two different lists
    In Python, it's a common task to separate even and odd numbers from a given list into two different lists. This problem can be solved using various methods. In this article, we’ll explore the most efficient ways to split even and odd elements into two separate lists. Using List ComprehensionList com
    3 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
  • 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
  • Python Program to Split each word according to given percent
    Given Strings with words, the task is to write a Python program to split each word into two halves on the basis of assigned percentages according to the given values. Example: Input : test_str = 'geeksforgeeks is best for all geeks and cs students', per_splt = 50Output : geeksf orgeeks i s be st f o
    6 min read
  • Python - Split list into all possible tuple pairs
    Given a list, the task is to write a python program that can split it into all possible tuple pairs combinations. Input : test_list = [4, 7, 5, 1, 9] Output : [[4, 7, 5, 1, 9], [4, 7, 5, (1, 9)], [4, 7, (5, 1), 9], [4, 7, (5, 9), 1], [4, (7, 5), 1, 9], [4, (7, 5), (1, 9)], [4, (7, 1), 5, 9], [4, (7,
    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
  • Python program to split a string by the given list of strings
    Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
    4 min read
  • Python program to reverse a range in list
    Reversing a specific range within a list is a common task in Python programming that can be quite useful, when data needs to be rearranged. In this article, we will explore various approaches to reverse a given range within a list. We'll cover both simple and optimized methods. One of the simplest w
    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