Home > front end >  How to print specific range of values in a 1 dimensional array in Python?
How to print specific range of values in a 1 dimensional array in Python?

Time:05-22

Given the array below:

array= [1,2,3,4,5,6,7,8]

Using Python, how to print the 3rd to the 6th element of the array? ie:

3, 4, 5, 6

CodePudding user response:

You can use python list slices to get the desired set of numbers, so in your case, you can do the next:

a = array[2:6]

Now you have the items that you want in the array and print them as you like, printing the full array or printing them one by one iterating over the array. Even you can print them directly with:

print(array[2:6])

CodePudding user response:

In python array is actually a list so you could utilize list indexing:

>>> array = [1, 2, 3, 4, 5, 6, 7, 8]
>>> array[2:6]
[3, 4, 5, 6]
  • Related