6

Code

#Variables
var1 = ['Warehouse Pencil 1.docx', 'Production Pen 20.docx']

list1 = []
for x in var1:
    splitted = x.split()
    a = [splitted[0] + ' ' + splitted[1]]
    list1.append(a)
    print(list1)

Output

[['Warehouse Pencil']]
[['Warehouse Pencil'], ['Production Pen']]

Goal

I am intending to split the list, grab the 1st and 2nd words for each section, and put them into a new list.

Question

Why is my output giving me a weird output? Where am I going wrong?

Desired Output

My desired output should look like this:

['Warehouse Pencil', 'Production Pen']

Grabbing the 1st and 2nd words and put them into 1 list.

CDJB
  • 12,538
  • 5
  • 20
  • 42
LV98
  • 887
  • 5
  • 19

3 Answers3

14

This should fix it - move the print statement out of the loop, and make a a string rather than a list.

#Variables
var1 = ['Warehouse Pencil 1.docx', 'Production Pen 20.docx']

list1 = []
for x in var1:
    splitted = x.split()
    a = splitted[0] + ' ' + splitted[1]
    list1.append(a)
print(list1)

Output:

['Warehouse Pencil', 'Production Pen']

You could also use a list comprehension:

>>> [' '.join(x.split()[:2]) for x in var1]
['Warehouse Pencil', 'Production Pen']
CDJB
  • 12,538
  • 5
  • 20
  • 42
  • Thank you, I see you removed the `[]` and also moved indentation for the print. How did the indentation matter in this scenario? Just curious – LV98 Dec 05 '19 at 12:59
  • 1
    @LV98 the indentation matters here because otherwise the list `list1` is printed every time the `for` loop runs. Moving it outside that loop means that it's only printed once, after the loop finishes. – CDJB Dec 05 '19 at 13:00
  • thanks for the explanation! and also what is happening at list comprehension? – LV98 Dec 05 '19 at 13:02
  • 2
    The list comprehension is basically a way of condensing a loop which fills a list into one line. You can read more about them [here](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – CDJB Dec 05 '19 at 13:05
0

You can also use the method str.rfind(sub). It returns the highest index in the string where substring sub (space in your case) is found:

[i[:i.rfind(' ')] for i in var1]
# ['Warehouse Pencil', 'Production Pen']

Alternatively, you can use the method str.rsplit(). It splits the string starting from the right:

[i.rsplit(maxsplit=1)[0] for i in var1]
# ['Warehouse Pencil', 'Production Pen']
Mykola Zotko
  • 8,778
  • 2
  • 14
  • 39
0

To get the filename. We can use the following approach.

import pathlib

var1 = ['Warehouse Pencil 1.docx', 'Production Pen 20.docx']
file_name = []

for i in var1:
    p = pathlib.Path(i)
    file_name.append(p.stem)
    
print(file_name)
['Warehouse Pencil 1', 'Production Pen 20']

[Program finished]
Subham
  • 125
  • 1
  • 1
  • 11