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

Here, we will figure out how to make a list from the predetermined begin to end record of another (given) list in Python.

Given a list, start and end a record, we need to make a list from an indicated list of the list in Python.

Example No. 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 No. 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

Rationale:

  • Take a list, start and end records of the list.
  • Check the limits of start and end file, if start file is under 0, print the message and stop the program, and if end file is more prominent than the length-1, print the message and stop the program.
  • To make a list from another list with given beginning and end lists, use list[n1:n2] documentation, in the program, the files are start and end.
  • Consequently, the announcement to make list is list1 = list[start: end+1].
  • At last, print the lists.

Program:

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

start = 1
end = 4

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

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

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

# printth lists 
print "list : ", list
print "list1: ", list1

Output:

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

Test with the invalid list

Size of the list is 6, and lists are from 0 to 5, in this example, the end record is invalid (which is 6), along these lines program will print “Invalid end file” and quit.

Note: Program may give the right output if the end list is more noteworthy than the length-1 of the list. Be that as it may, to execute the program with no issue, we ought to approve the beginning and end record.

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

start = 1
end = 6

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

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

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

# printth lists 
print "list : ", list
print "list1: ", list1

Output:

    Invalid end index

Leave a Comment

error: Alert: Content is protected!!