0

This is my first post so I will most likely do something wrong. I am wondering if there is a faster way to remove items from a list based on their position. I am relatively new to python so I most likely have overlooked a faster way.

Stack3 = (Cards[0],Cards[1],Cards[2])
while Count < 3:
    Cards.pop(0)
    Count += 1
Count = 0

This is what my current code is. As you can see, I am just removing the first item from the list many times over. This seems very messy and unorganized to me. I would really appreciate any help, thanks!

Jax
  • 57
  • 7

1 Answers1

3

Removing elements from a list while looping is not a good practice. A better way to do it is to use a list comprehension:

lst = [1,2,3,4,5,6,7]
indices_to_remove = [3,4,1]

lst = [elem for index,elem in enumerate(lst) if index not in indices_to_remove]

Output:

>>> lst
[1, 3, 6, 7]
Sushil
  • 5,440
  • 1
  • 8
  • 26