Carlos Eduardo Corpus
Carlos Eduardo Corpus

Reputation: 349

Creating a 2D list from a 2D list using list comprehension

So I have a 2D list with some elements with lenght zero and others not, I want to create a 2D list by creating pairs of the elements which lenght is greater than 2, but conserving those with lenght zero, here is an example and what I tried:

mylist = [[], [3, 2, 4], [], [], [3, 2, 4], []] #2D list

newlist = [x[idx: idx+2] if len(x) >= 2 else [] for x in mylist for idx in range(0, len(x) - 1) ] #This tries to create the 3D list

print(newlist)

#newlist = [[3, 2], [2, 4], [3, 2], [2, 4]] #doesn't have the list with lenght zero

my desired result should be something like this

newlist = [[], [3, 2], [2, 4], [], [], [3, 2], [2, 4], []]

my initial list can be different, another valid example is this:

mylist = [[1, 2], [3, 2, 4], [3, 4], [3, 2, 4], [1, 2, 3, 4]] 

I have tried changing the if else condition, but nothing seems to work, so any help would be appreciated, thank you!

Edit: The list may be different, it may have elements with lenght zero or not, by creating pairs I mean that if I have lists something like:

l1 = [2, 3, 4] it will create the pairs [[2,3], [3, 4]]
l2 = [2, 3, 4, 5] it will create the pairs [[2, 3], [3, 4], [4, 5]]

Upvotes: 0

Views: 76

Answers (2)

user15801675
user15801675

Reputation:

You basically need to check for the length of val before you go on.

mylist = [[], [3, 2, 4], [], [], [3, 2, 4], []] #2D list


nex_list=[]
for val in mylist:
    if len(val)>=2: #=== len of val
        for idx in range(0, len(val)-1):
            nex_list.append(val[idx: idx+2])
    else:
        nex_list.append([]) #=== Add empty list to new list
print(nex_list)

Output

[[], [3, 2], [2, 4], [], [], [3, 2], [2, 4], []]

Upvotes: 1

user1763510
user1763510

Reputation: 1260

I probably wouldn't use a list comprehension for this, but if you want to this works:

mylist = [[], [3, 2, 4], [], [], [3, 2, 4], []]
newlist = [k[j:j+2] if len(k)>0 else [] for k in mylist for j in range(max(1,len(k)-1))]

Output:

[[], [3, 2], [2, 4], [], [], [3, 2], [2, 4], []]

The max(1,len(k)-1) ensures that we have 1 j value for the empty list and len(k)-1 for the non-empty lists.

Upvotes: 2

Related Questions