Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a new list while iterating over another list?

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.

like image 646
EdGzi Avatar asked Dec 05 '19 12:12

EdGzi


2 Answers

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']
like image 180
CDJB Avatar answered Nov 02 '22 23:11

CDJB


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']
like image 43
Mykola Zotko Avatar answered Nov 03 '22 01:11

Mykola Zotko