In this post, I’ll show you how to return the common list items between two lists in Python.
fruits1 = ['Apple', 'Banana', 'Orange', 'Kiwi', 'Pineapple'] fruits2 = ['Apple', 'Mango', 'Orange', 'Pear', 'Strawberry'] items_in_both_lists = list(set(fruits1).intersection(fruits2)) print(items_in_both_lists) >> ['Orange', 'Apple']
The lists get converted to sets in order to leverage the intersection function which will return similar items from both sets.
For those working with Pandas, I found this to be extremely helpful when working with the categories data type. If you try and reorder your categories based on items that aren’t in your column, you will get an error. To get around that, you can compare your desired list to the unique values in your DataFrame column:
desired_order = ['Apple', 'Banana', 'Orange', 'Kiwi', 'Pineapple'] unique_column_items = df['column1'].unique().tolist() fruit_order = list(set(desired_order).intersection(unique_column_items)) df['column1'] = df['column1'].astype('category') df['column1'].cat.remove_unused_categories(inplace=True) df['column1'].cat.reorder_categories(fruit_order, inplace=True)
Thanks for reading!