list_example = ["python","ruby","java","javascript","c#","css","html"]
print(list_example[3])#javascript
print(list_example[0])#python
print(list_example[6])#html
print(list_example[0:3]) #will print the programming language under python and javascript
print(list_example[:3]) all languages under python to javascript
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements from index 2 to index 4
print(my_list[2:5])
# elements from index 5 to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
#slicing arrays:
#generic sampling is done by
#arr[start:end] -> where start is the starting index and end is ending idx
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
>>> print(arr[1:5]) #starting idx 1 to ending index 4
[2 3 4 5]#it will print from starting idx to ending idx-1
#if you leave the ending index blank it will print all
#from the starting index till end
>>> arr = np.array([2,6,1,7,5])
>>> print(arr[3:])
[7 5]
>>> print(arr[:3]) #if you leave the starting index blank it will print from 0 index to the ending idx-1
[2 6 1]
>>> print(arr[:])
[2 6 1 7 5]
#leaving both the index open will print the entire array.
##########STEP slicing########
#if you want to traverse by taking steps more than 1
#we use step slicing in that case
#syntax for step slicing is : arr[start:end:step]
>>> arr = np.array([2,6,1,7,5,10,43,21,100,29])
>>> print(arr[1:8:2])#we have taken steps of two
[ 6 7 10 21]
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements from index 2 to index 4
print(my_list[2:5])
# elements from index 5 to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
#['o', 'g', 'r']
#['a', 'm', 'i', 'z']
#['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
# Python program to demonstrate
# Removal of elements in a List
# Creating a List
List = ['S','O','F','T','H','U',
'N','T','.','N','E','T']
print("Initial List: ")
print(List)
# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("
Slicing elements in a range 3-8: ")
print(Sliced_List)
# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("
Elements sliced from 5th "
"element till the end: ")
print(Sliced_List)
# Printing elements from
# beginning till end
Sliced_List = List[:]
print("
Printing all elements using slice operation: ")
print(Sliced_List)
This slice object can take three arguments;
slice(start, end, step)
fruits = ["apple", "banana", "peach", "pear", "plum", "orange"]
x = slice(1, 4, 2)
fruits[x]
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
# Output: ('r', 'o', 'g')
print(my_tuple[1:4])
# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])
# elements 8th to end
# Output: ('i', 'z')
print(my_tuple[7:])
# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])