Python | Create two lists with first half and second half elements of a list

Here, we are going to learn how to create two lists with first half and second half elements of a given list in Python? By IncludeHelp Last updated : June 22, 2023

Given a list, and we have to create two lists from first half elements and second half elements of a list in Python.

Example:

Input:
list:  [10, 20, 30, 40, 50, 60]

Output:
list1: [10, 20, 30]
list2: [40, 50, 60]

Logic:

  • First take list (Here, we are taking list with 6 elements).
  • To get the elements from/till specified index, use list[n1:n2] notation.
  • To get first half elements, we are using list[:3], it will return first 3 elements of the list.
  • And, to get second half elements, we are using list[3:], it will return elements after first 3 elements. In this example, we have only 6 elements, so next 3 elements will be returned.
  • Finally, print the lists.

Program:

# define a list
list = [10, 20, 30, 40, 50, 60]

# Create list1 with half elements
# (first 3 elements)
list1 = list[:3]
# Create list2 with next half elements
# (next 3 elements)
list2 = list[3:]

# print list (s)
print("list : ", list)
print("list1: ", list1)
print("list2: ", list2)

Output

list :  [10, 20, 30, 40, 50, 60]
list1:  [10, 20, 30]
list2:  [40, 50, 60]

Using list[0:3] and list[3:6] instaed of list[:3] and list[3:]

We can also use list[0:3] instead of list[:3] to get first 3 elements and list[3:6] instead of list[3:] to get next 3 elements after first 3 elements.

Consider the program:

# define a list
list = [10, 20, 30, 40, 50, 60]

# Create list1 with half elements
# (first 3 elements)
list1 = list[0:3]
# Create list2 with next half elements
# (next 3 elements)
list2 = list[3:6]

# print list (s)
print("list : ", list)
print("list1: ", list1)
print("list2: ", list2)

Output

list :  [10, 20, 30, 40, 50, 60]
list1:  [10, 20, 30]
list2:  [40, 50, 60]

By considering length of the list

Let suppose list has n elements, then we can use list[0:n/2] and list[n/2:n].

Consider the program:

If there are ODD numbers of elements in the list, program will display message "List has ODD number of elements." And exit.

# define a list
list = [10, 20, 30, 40, 50, 60]

# get the length of the list
n = len(list)

# condition to check length is EVEN or not
# if lenght is ODD, show message and exit
if n % 2 != 0:
    print("List has ODD number of elements.")
    exit()

half = int(n / 2)

# Create list1 with half elements
# (first 3 elements)
list1 = list[0:half]
# Create list2 with next half elements
# (next 3 elements)
list2 = list[half:n]

# print list (s)
print("list : ", list)
print("list1: ", list1)
print("list2: ", list2)

Output

list :  [10, 20, 30, 40, 50, 60]
list1:  [10, 20, 30]
list2:  [40, 50, 60]

Python List Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.