xxxxxxxxxx
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = [lst[i] for i in indices]
xxxxxxxxxx
# define a list
my_list = [1, 2, 3, 4, 5]
# get a slice of the list
sublist = my_list[1:3]
print(sublist) # [2, 3]
# get a slice from the beginning of the list
sublist = my_list[:3]
print(sublist) # [1, 2, 3]
# get a slice from the end of the list
sublist = my_list[3:]
print(sublist) # [4, 5]
# get a slice from the middle of the list
sublist = my_list[1:-1]
print(sublist) # [2, 3, 4]
# get the last two elements of the list
sublist = my_list[-2:]
print(sublist) # [4, 5]
# get all elements except the last two
sublist = my_list[:-2]
print(sublist) # [1, 2, 3]
xxxxxxxxxx
# 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']
xxxxxxxxxx
# 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("\nSlicing elements in a range 3-8: ")
print(Sliced_List)
# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_List)
# Printing elements from
# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)
xxxxxxxxxx
# Python's list slice syntax can be used without indices
# for a few fun and useful things:
# You can clear all elements from a list:
list = [1, 2, 3, 4, 5]
del lst[:]
print(list)
# Output
# []
# You can replace all elements of a list
# without creating a new list object:
a = list
lst[:] = [7, 8, 9]
print(list)
# Output
# [7, 8, 9]
print(a)
# Output
# [7, 8, 9]
print(a is list)
# Output
# True
# You can also create a (shallow) copy of a list:
b = list[:]
print(b)
# Output
# [7, 8, 9]
print(b is lst)
# Output
# False