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:
Output
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:
Output
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.
Output
need an explanation for this answer? contact us directly to get an explanation for this answer