Here, we will figure out how to make two lists with the first half and second half components of a given list in Python?
Given a list, and we need to make two lists from first half components and second half components of a list in Python.
Example:
Input:
list: [10, 20, 30, 40, 50, 60]
Output:
list1: [10, 20, 30]
list2: [40, 50, 60]
Rationale:
- First take a list (Here, we are taking the list with 6 components).
- To get the components from/till indicated list, use list[n1:n2] documentation.
- To get the first half components, we are utilizing list[:3], it will return the initial 3 components of the list.
- What’s more, to get second half components, we are utilizing list[3:], it will return components after initial 3 components. In this example, we have just 6 components, so the next 3 components will be returned.
- At last, 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]
Utilizing list[0:3] and list[3:6] instead of list[:3] and list[3:]
We can likewise utilize list[0:3] rather than list[:3] to get initial 3 components and list[3:6] rather than list[3:] to get next 3 components after initial 3 components.
Think about 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 thinking about the length of the list:
Let guess list has n components, at that point we can utilize list[0:n/2] and list[n/2:n].
Think about the program:
On the off chance that there are ODD quantities of components in the list, the program will show the message “List has an ODD number of components.” 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()
# Create list1 with half elements (first 3 elements)
list1 = list [0:n/2]
# Create list2 with next half elements (next 3 elements)
list2 = list [n/2: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]