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[:])
word = "Example"
# Obtain the first 3 characters of "Example"
# E x a m p l e
# 0 1 2 3 4 5 6
# First 3 characters = "Exa"
sliced_word = word[:3] # Gives you "Exa"
# Everything after character #3 = "mple"
second_sliced_word = word[3:] # Gives you "mple"
# 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']
In Python, we perform slicing using the following syntax: [start: end].
fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]
sliced_fruits = fruits[1:3]
print(sliced_fruits) # ["Orange", "Lemon"]
Slicing in Python is very flexible. If we want to select the first n elements
of a list or the last n elements in a list, we could use the following code:
fruits[:n]
fruits[-n:]
fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]
print(fruits[:3])
# ["Banana", "Orange", "Lemon"]
print(fruits[-2:])
# ["Apple", "Mango"]
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[:])