Python | Create a list from the specified start to end index of another list

Here, we are going to learn how to create a list from the specified start to end index of another (given) list in Python. By IncludeHelp Last updated : June 22, 2023

Given a Python list, start and end index, we have to create a list from the specified index of the list.

Example 1

Input:
list : [10, 20, 30, 40, 50, 60]
start = 1
end = 4

Logic to create list with start and end indexes:
List1 = list[start: end+1]

Output:
list1: [20, 30, 40, 50]

Example 2

Input:
list : [10, 20, 30, 40, 50, 60]
start = 1
end   = 6

Logic to create list with start and end indexes:
list1 = list[start: end+1]

Output:
Invalid end index

Logic

  • Take a list, start and end indexes of the list.
  • Check the bounds of start and end index, if start index is less than 0, print the message and quit the program, and if end index is greater than the length-1, print the message and quit the program.
  • To create a list from another list with given start and end indexes, use list[n1:n2] notation, in the program, the indexes are start and end. Thus, the statement to create list is list1 = list[start: end+1].
  • Finally, print the lists.

Python program to create a list from the specified start to end index of another list

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

start = 1
end = 4

if start < 0:
    print("Invalid start index")
    quit()

if end > len(list1) - 1:
    print("Invalid end index")
    quit()

# create another list
list2 = list1[start : end + 1]

# printth lists
print("list1 : ", list1)
print("list2: ", list2)

Output

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

Test with the invalid index

Size of the list is 6, and indexes are from 0 to 5, in this example the end index is invalid (which is 6), thus program will print "Invalid end index" and quit.

Note: Program may give correct output if end index is greater than the length-1 of the list. But, to execute program without any problem, we should validate the start and end index.

To get the length of a list, use len() method.

Example

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

start = 1
end = 6

if start < 0:
    print("Invalid start index")
    quit()

if end > len(list1) - 1:
    print("Invalid end index")
    quit()

# create another list
list2 = list1[start : end + 1]

# printth lists
print("list1 : ", list1)
print("list2: ", list2)

Output

Invalid end index

Python List Programs »


Related Programs

Comments and Discussions!

Load comments ↻






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