GJury
GJury

Reputation: 55

Unpack list from single line list comprehension

Python beginner here. I have a list of lists that I am trying to filter based on the value in mylist[x][0], plus add an index value to each resulting sublist. Given the following list comrehension:

shortlist = [[x, mylist[x]] for x in range(1,20) if mylist[x][0] == 'TypeB']

I get the following output:

[[11, ['TypeB', 'Kline', '', '', 'Category']],
 [12, ['TypeB', '', '[Aa]bc', '', 'Category3']],
 [13, ['TypeB', '', '[Z]bc', '', 'Category']],
 [14, ['TypeB', '', 'Kline', '[Aa]bc', 'Category4']],
 [15, ['TypeB', '', '', '[Z]bc', 'Category']],
 [16, ['TypeB', '', '', 'Kline', 'Category5']],
 [17, ['TypeB', '[Aa]bc', '', '', 'Category']],
 [18, ['TypeB', '[Z]bc', '', '', 'Category2']],
 [19, ['TypeB', 'Kline', '', '', 'Category']]]

This creates a sub-sublist that I guess I need to unpack somehow with more lines of code, but I'd rather not do that if I can just correct the list comprehension. My goal would be to have the first "line" read

[[11, 'TypeB', 'Kline', '', '', 'Category'],

...and the rest of the output follow suit. My attempts at

shortlist = [x, mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

and

shortlist = [x for x in range(1,20) if mylist[x][0] == 'TypeB', mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

both give syntax errors. Obviously I am new to list comprehensions. I value any input and guidance. Thank you in advance for your time.

Upvotes: 4

Views: 2135

Answers (2)

SCB
SCB

Reputation: 6139

You need to concatenate your inner lists together. A few ways to do this depending on the version of python you're using.

shortlist = [[x, *mylist[x]] for x in range(1,20) if mylist[x][0] == 'TypeB']

Will unpack all the values of mylist[x] into the list. Probably the most "pythonic" way, however will only work from python 3.5 up.

shortlist = [[x] + mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

Will create a list with just x in it, and then add mylist[x] onto the end.

Upvotes: 4

user2390182
user2390182

Reputation: 73450

Judging from your output, this should work:

shortlist = [[x] + mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

When [x, mylist[x]] yields [11, ['TypeB', 'Kline', '', '', 'Category']], you know that

 x         -> 11
 mylist[x] -> ['TypeB', 'Kline', '', '', 'Category']

Hence, you want to wrap x in a list and concatenate it with the other.

Upvotes: 4

Related Questions