0

like this: I would like to remove a certain number of items

abc_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
abs_list =- 7

that should be the result

result = ["a", "b", "c"]
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201

2 Answers2

2

You can use negative slicing to index from the back

>>> abc_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> abc_list[:-6]
['a', 'b', 'c']
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
0

Use slicing to get a list with the first n elements.

abc_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
# get a list with the first n elements (where the last m are removed)
first_3 = abc_list[:3]  # elements until the 3rd (inclusive), so n = 3
last_6_removed = abc_list[:-6] # elements until the 6th from back, so m = 6

In [s:e] the s is the start index, the e is the end index. The index can be negative indicating reverse direction ("from back"). All elements between s and e are returned - slicing.

If the start or end is omitted, it will slice unbounded (without start or end as boundary).

See also:

Real Python: Indexing and Slicing, tutorial

hc_dev
  • 5,553
  • 20
  • 27