22. List slicing (selecting parts of lists)

Section 22.1: 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’]

Section 22.2: 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’]

Section 22.3: Reversing a list with slicing

[12345]

#steps through the list backwards (step=-1) a[::-1]

#built-in list method to reverse ‘a’ a.reverse()

if b: print(True)

print(b)

#Output:

#True

#[5, 4, 3, 2, 1]

Section 22.4: Shifting a list using slicing

def shift_list(arrays):

“””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 [12345]

# negative numbers

shift_list(my_array7)

>>>[34512]

#no shift on numbers equal to the size of the arrayshift_list(my_array5)

>>> [12345]

#works on positive numbers

shift_list(my_array3)

>>> [34512]

 

 

 

 

 

*This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow. 

  *This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow.  This work is licensed under cc by-sa.