Q:

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

belongs to collection: Python List Programs

0

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

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

# 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Create three lists of numbers, their squa... >>
<< Python | Program to print all numbers which are di...