-1

Suppose there is a list

primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']

now If I waned to separate elements with ".txt " to get into a new separate list how can I do that?

Saksham Kushwaha
  • 274
  • 1
  • 18
  • 1
    Do you want to modify this list to remove items not required, or do you want a new list with just the things you want? – quamrana Apr 17 '21 at 19:54
  • @quamrana Ya you can say that I want to modify this list by removing element I don't want those elements are those which don't have any extension with them. – Saksham Kushwaha Apr 17 '21 at 19:55
  • no it doesn't answer my question the answer below is what I was looking for. – Saksham Kushwaha Apr 17 '21 at 20:07
  • Ok, but the question I linked to was primarily answered with list comprehensions which created new lists. Very few modified the list. – quamrana Apr 17 '21 at 20:09

2 Answers2

2

As shown in Nk03's answer and quamrana's comment, you can use list comprehension to create a new list. To add to this, if you would like to filter specifically a suffix, use the endswith() method. Otherwise, items will get filtered out, even if .txt happens to appear somewhere else in the text.

primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
new_list = [item for item in primary_list if not item.endswith('.txt')]
new_list_two = [item for item in primary_list if item.endswith('.txt')]
print(new_list)
print(new_list_two)

Output:

['f1', 'f2', 'f3']
['t1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
yagus
  • 1,417
  • 6
  • 14
1

you can use list comprehension with string split method -

new_list_without_txt = [item for item in primary_list if '.txt' not in item ]
new_list_with_txt = [item for item in primary_list if '.txt' in item ]
print(new_list_without_txt)
print(new_list_with_txt)

output--

['f1', 'f2', 'f3']
['t1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
new_list = [item.split('.txt')[0] if '.txt' in item else item for item in primary_list]
print(new_list)

output -

['f1', 'f2', 'f3', 't1', 't2', 't3', 't4', 't5']
Nk03
  • 14,699
  • 2
  • 8
  • 22