Python Forum
How to remove some elements from an array in python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to remove some elements from an array in python?
#2
Please use bbtags when posting code.

Here is one way

# Create a list
alist = [i for i in range(50)]
sorted(alist)

print(alist)
print()
# Create a copy of the list.
# Should not try to edit a list that you are iterating over
alist_copy = alist.copy()

# Iterate over the copy and remove anything above chosen number
# from original list
for index, number in enumerate(alist_copy):
    if number > 20:
        alist.remove(number)

print(alist)
Output
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
gohanhango likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply


Messages In This Thread
RE: How to remove some elements from an array in python? - by menator01 - Nov-28-2023, 12:17 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 1,836 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 8,655 May-17-2022, 11:38 AM
Last Post: Larz60+
  Replace elements of array with elements from another array based on a third array Cola_Reb 6 5,815 May-13-2022, 06:06 PM
Last Post: deanhystad
Question Change elements of array based on position of input data Cola_Reb 6 3,637 May-13-2022, 12:57 PM
Last Post: Cola_Reb
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 10,441 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  Sorting Elements via parameters pointing to those elements. rpalmer 3 3,624 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  4D array with only elements on one side of the diagonal schniefen 0 2,245 Dec-24-2020, 11:32 AM
Last Post: schniefen
  Removing some elements from array based on a condition claw91 0 2,219 Oct-27-2020, 03:42 PM
Last Post: claw91
  Remove specific elements from list with a pattern Xalagy 3 3,768 Oct-11-2020, 07:18 AM
Last Post: Xalagy
  remove elements method not working spalisetty06 4 3,627 Aug-13-2020, 01:17 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020