Bijan
Bijan

Reputation: 8602

Create list from 2D list based on conditions

I have a 2D Array in Python that is set up like

MY_ARRAY = [
    ['URL1', "ABC"],
    ['URL2'],
    ['URL3'],
    ['URL4', "ABC"]
]

I want to make an array of first element of each array only if the 2nd parameter is "ABC". So the result of the above example would be ['URL1', 'URL4']

I tried to do [x[0] for x in MY_ARRAY if x[1] == 'ABC'] but this returns IndexError: list index out of range. I think this is because sometimes x[1] is nonexistant.

I am looking for this to be a simple one-liner.

Upvotes: 1

Views: 817

Answers (5)

Bijan
Bijan

Reputation: 8602

I found a simple solution that works for my usage.

[x[0] for x in MY_ARRAY if x[-1] == 'ABC']

x[-1] will always exist since thats the last element in the array/list.

Upvotes: 0

miradulo
miradulo

Reputation: 29690

You could simply add a length check to the filtering criteria first. This works because Python short-circuits boolean expressions.

[ele[0] for ele in MY_ARRAY if len(ele) > 1 and ele[1] == 'ABC']

Also note that the proper terminology here is a list of lists, not an array.

Upvotes: 2

Jomark
Jomark

Reputation: 31

I think you should try doing this:

if len(x) > 1:
    if x[1] == 'ABC':
        #do something here

This is a work around, but you can try it on one-liner code using:

if len(x) > 1 and x[1] == "ABC"

Cheers!

Upvotes: 2

Ofer Sadan
Ofer Sadan

Reputation: 11932

First, let me tell you are on the right track, when x[1] doesn't exist you get the error

But, it's a bad habit to insist on doing things as a one-liner if it complicates matters.

Having said that, here's a one-liner that does that:

NEW_ARRAY = [x[0] for x in MY_ARRAY if len(x)>1 and x[1]=='ABC']

Upvotes: 1

viveksyngh
viveksyngh

Reputation: 787

Try this

[x[0] for x in MY_ARRAY if len(x) > 1 and x[1] == 'ABC']

It is happening because you have two list are having only one item and you are trying to access second item from that list

Upvotes: 1

Related Questions