Python List slicing (selecting parts of lists)

List slicing (selecting parts of lists) is useful in performing different tasks and getting desired outputs. Learn more about Python List slicing here.

What is slicing of list in python?

List slicing refers to accessing a specific portion or a subset of the list for some operation while the orginal list remains unaffected. The slicing operator in python can take 3 parameters out of which 2 are optional depending on the requirement.

How can a list be sliced in Python?

How to slice a list, string, tuple in Python

  1. Basic usage of slicing. Start position start and end position stop. step.
  2. Select from the end with a negative value. Negative values for start and stop. Negative values for step.
  3. Slice object by slice()
  4. Assigning values by slicing.
  5. Slicing for strings and tuples.

Python List slicing: Using the third “step” argument

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
lst[::2]

Output: [‘a’, ‘c’, ‘e’, ‘g’]

lst[::3]

Output: [‘a’, ‘d’, ‘g’]

Selecting a sublist from a list

lst = ['a', 'b', 'c', 'd', 'e']
lst[2:4]

Output: [‘c’, ‘d’]

lst[2:]

Output: [‘c’, ‘d’, ‘e’]

lst[:4]

Output: [‘a’, ‘b’, ‘c’, ‘d’]

Python List slicing: Reversing a list with slicing

a = [1, 2, 3, 4, 5]
steps through the list backwards (step=-1) b = a[::-1]
built-in list method to reverse 'a' a.reverse()
if a = b:
print(True)
print(b)
Output:
True
[5, 4, 3, 2, 1]

Python List slicing: Shifting a list using slicing

def shift_list(array, s):
"""Shifts the elements of a list to the left or right.
Args:
array - the list to shift
s - the amount to shift the list ('+': right-shift, '-': left-shift)
Returns:
shifted_array - the shifted list

“””

calculate actual shift amount (e.g., 11 --> 1 if length of the array is 5) s %= len(array)
reverse the shift direction to be more intuitive
s *= -1
shift array with list slicing shifted_array = array[s:] + array[:s]
return shifted_array
my_array = [1, 2, 3, 4, 5]

negative numbers

shift_list(my_array, -7)
[3, 4, 5, 1, 2]
no shift on numbers equal to the size of the array shift_list(my_array, 5)
[1, 2, 3, 4, 5]
works on positive numbers
shift_list(my_array, 3)
[3, 4, 5, 1, 2]


Example

# Initialize list
List = ['Geeks', 4, 'geeks !']

# Show original list
print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

# Display sliced list
print(List[::-1])

# Display sliced list
print(List[::-3])

# Display sliced list
print(List[:1:-2])

OUT PUT

Original List:
 ['Geeks', 4, 'geeks !']

Sliced Lists: 
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here