Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How to copy elements from list that start with a certain letter into new list or remove elements from list that do not start with letter

I am getting a list from an excel file using pandas.

start_path = r'C:\scratch\\'
File = 'test.xlsx'
import pandas as pd 
mylist = []
df = pd.read_excel(start_path + File, sheet_name='GIS')
mylist = df['Column A'].tolist()

List:

mylist = ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56', 'ABC']

My goal is to then create a new list from this list, only with the elements that start with LB. So the new list would then be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

newlist = ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']

Or just remove all elements from a list that do not start with ‘LB’ (thus removing ABC from the list).

newlist = [str(x for x in mylist if "LB" in x)]

I tried the above and this just spits out:

['<generator object <genexpr> at 0x0000024B5B8F62C8>']

I also have tried the following:

approved = ['LB']
mylist[:] = [str(x for x in mylist if any(sub in x for sub in approved))]

This gets the same generator object message as before.

I feel like this is really simple but cannot figure it out.

>Solution :

You can use str.startswith in list-comprehension:

mylist = ["LB-52/LP-7", "LB-53/LI-5", "LB-54/LP-8", "LB-55", "LB-56", "ABC"]

newlist = [value for value in mylist if value.startswith("LB")]
print(newlist)

Prints:

['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']

You can remove str() in newlist = [str(x for x in mylist if "LB" in x)] but this will leave values such as xxxLBxxx (LB is inside the string)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading