spiral01
spiral01

Reputation: 545

Python: Test for equality of certain index in nested lists

I have the following nested list:

nlist = [[2, 0, 4], [2, 0, 4], [0, 0, 4], [0, 0, 4]]

I would like to evaluate whether the first element of each list is equal. I have found methods to evaluate whether the entire nested lists are equal, but not specific indexes?

Upvotes: 2

Views: 1175

Answers (4)

Kobi Moshe
Kobi Moshe

Reputation: 36

first_num = nlist[0][0]
for sublist in nlist:
    if first_num != sublist[0]
        print(False)
print(True)

Upvotes: 0

Dadep
Dadep

Reputation: 2788

you can find all the unique first element and then check index :

>>> from itertools import groupby
>>> nlist = [[2, 0, 4], [2, 0, 4], [0, 0, 4], [0, 0, 4]]
>>> c= [i for i,k in groupby([n[0] for n in nlist])]
>>> c
[2, 0]
>>> d=[[i for i, x in enumerate(nlist) if x[0]==j] for j in c]
>>> d
[[0, 1], [2, 3]]
>>> R=dict(zip(c, d))
>>> R
{0: [2, 3], 2: [0, 1]}

you get a dict with each first possible value and a list of index from your initial list.

Upvotes: 0

Djaouad
Djaouad

Reputation: 22794

You could make a set of the first elements of each sub list, and since there is no repetition in sets, you can see if the length of the set is one:

nlist = [[2, 0, 4], [2, 0, 4], [0, 0, 4], [0, 0, 4]]

result = len(set(l[0] for l in nlist)) == 1
print(result) # => False

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168876

I would use the all() function with a generator expression as its parameter.

all(sublist[0] == nlist[0][0] for sublist in nlist)

In short, all() will return True if every sublist[0] == nlist[0][0] for every sublist in the original list. It will return False if any item is not equal to nlist[0][0].

Upvotes: 2

Related Questions