Slicing oprations a Python list

The slicing operations on a Python list returns slices specified by the indexes. The slices themselves are new while the elements in them are shallow copies of the original.

List Updated 21 Jul 2021 1 min read

Overview

  • Slicing operations on a list using a begin index and end index returns list slices containing shallow copies of list elements.

Example

python
# A list of things as seen from the window

            view = ["sky", "cloud", "rain", "rainbow", "sun", "aircraft", "trees"]

print("List elements:");

            print(view);

# Take few elements from the middle

            slice = view[2:4]

            print(slice)

# Take few elements from the last

            slice = view[5:7]

            print(slice)

# Take few elements from the beginning

            slice = view[0:2]

            print(slice)

# Extract few elements from the beginning

            slice = view[-6:-3]

            print(slice)

Output

Output
List elements:

['sky', 'cloud', 'rain', 'rainbow', 'sun', 'aircraft', 'trees']

['rain', 'rainbow']

['aircraft', 'trees']

['sky', 'cloud']

['cloud', 'rain', 'rainbow']