Solved

Deleting all members of a list that are of a particular type

Posted on 2006-07-12
1
185 Views
Last Modified: 2010-04-16
Hi there,

Let's say I have a list:

foodlist = ['Fruit', 'Vegetable', 'Fish', 'Pasta', 'Rice_', 'Water', 'Meat_', 'Chocolate']

How would I create a new list that contains members of foodlist that DO NOT end in _  ?    (i.e., the new list would have all members of foodlist except for 'Rice_' and 'Meat_')

newList = ['Fruit', 'Vegetable', 'Fish', 'Pasta', 'Water', 'Chocolate']


newList = []
for food in foodlist:
    if food not ?
         newList.append(food)


It's probably really simple, but I am still novicish (a nice new word!) at Python,


Thanks,
John
0
Comment
Question by:JohnAutoSales
1 Comment
 
LVL 17

Accepted Solution

by:
ramrom earned 500 total points
ID: 17093393
newList = []
for food in foodlist:
    if not food.endswith("_"):
         newList.append(food)

OR

newlist = [food for food in foodlist if not food.endswith("_")]
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
A set of related code is known to be a Module, it helps us to organize our code logically which is much easier for us to understand and use it. Module is an object with arbitrarily named attributes which can be used in binding and referencing. …
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now