Slice The Lists


List Datatype

In python lists, data types are similar to arrays in C. It can contain data of different types. A comma separates the values (,) and it is enclosed within square braces ( [ ] ). We can use the slice operator (:) to access the data on the list. The plus (+) operator and the repetition operator(*) act the same way as in the strings.
List Slicing in python is very common and widely preferred by numerous programmers for solving problems. Slicing a list is essential to access a range of elements in it. With the slice operator (:), you can specify the starting and ending points for slicing, and then the new sliced list will be printed.
Furthermore, you can use negative indexing to find the reverse of a list using the slice operator. As -1 in a list represents the last element and –n represents its first element. Therefore, you can use these indexes to reverse the list.

Function slice( ): You can also use the slice() function for the same purpose. Its syntax is: slice(starting, stopping, steps). This function can take three parameters:

  • Start – It is the starting point from where the slicing is to be started. It defaults to None if it is left blank.
  • Stop –> It is the value till which the slicing is to be done. The slicing can continue maximum till the last element of the list.
  • Step – >It is the number of increments required between every index for slicing. It defaults to None if left blank.

Example:

b = "Knowledge2life, website" print(b[:14])

OUTPUT:

Knowledge2life