You can try this also:
new_list = []
for file in my_list:
if file.endswith(".txt"):
new_list.append(file)
print(new_list)
Output
['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt']
UPDATE:
You can also group all the files using a defaultdict, like this:
from collections import defaultdict
d = defaultdict(list)
for file in my_list:
key = "." + file.split(".")[1]
d[key].append(file)
print(d)
Output:
defaultdict(<class 'list'>, {'.txt': ['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt'], '.png': ['draw.png', 'figure.png']})
Or even with out a defaultdict:
d = {}
for file in my_list:
key = "." + file.split(".")[1]
if key not in d:
d[key] = []
d[key].append(file)
print(d)
Output:
{'.txt': ['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt'], '.png': ['draw.png', 'figure.png']}