简体   繁体   中英

Remove an element from a list and return the truncated list

I have:

inventory1=['AA','EA','RW','Others']

I need a list that contains all elements except 'Others'. In differing lists, the position of 'Others' is not fixed. Sometimes it is last, and at other times, it is somewhere else. The list above can contain a very large number of strings.

I tried,

inventory2=inventory1
inventory2.remove('Others')

Does not work.

inventory2=inventory1.remove('Others')

doesn't even return a list.

This should be simple to do. Yet, this is not working.

Just tried the following in Python3.5 (running it in terminal):

inventory1=['AA','EA','RW','Others']
inventory1.remove('Others')
inventory1

The output is:

['AA', 'EA', 'RW']

So, I don't see where the problem is, since it seems to work as intended. 'Others' gets removed. A more cumbersome way would be:

  inventory1=['AA','EA','RW','Others']
  del inventory1[inventory1.index('Others')]
  inventory1

The output is the same. For more information, see this post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM