arsenal88
arsenal88

Reputation: 1160

pythonic way to add elements to nested list

I have a nest list:

listSchedule = [[list1], [list2], etc..]]

I have another list and I want to append to each nested list the element of this list if the first element of each matches a string.

I can do it but I wonder if there is a more 'pythonic' way, using list comprehension?

index = 0;
for row in listSchedule:
   if row[0] == 'Download':
      row[3] = myOtherList[index]
      index +=1

Upvotes: 2

Views: 127

Answers (4)

Sasha Tsukanov
Sasha Tsukanov

Reputation: 1125

We can use a queue and pop its values one by one when we meet the condition. To avoid copying of data let's implement the queue as a view over myOtherList using an iterator (thanks to ShadowRanger).

queue = iter(myOtherList)

for row in listSchedule:
    if row[0] == "Download":
        row.append(next(iter))

Upvotes: 0

Frayal
Frayal

Reputation: 2161

you could try that but make a copy of the otherlist to not lose the info:

[row+[myotherlist.pop(0)] if row[0]=='Download' else row for row in listScheduel]

for example:

list = [['Download',1,2,3],[0,1,2,3],['Download',1,2,3],['Download',1,2,3]]
otherlist = [0,1,2,3,4]
l = [ row+[otherlist.pop(0)] if row[0]=='Download' else row for row in list]

Output:

[['Download', 1, 2, 3, 0],
[0, 1, 2, 3],
['Download', 1, 2, 3, 1],
['Download', 1, 2, 3, 2]]

Upvotes: 1

C.Nivs
C.Nivs

Reputation: 13106

If you want to truly append, why not use row.append(myOtherList[index])? That way you avoid IndexErrors

i = 0

for row in listSchedule:
    if row[0]=="Download":
        row.append(myOtherList[i])
        i+=1

Upvotes: 0

fafl
fafl

Reputation: 7385

Your code is very readable, I would not change it.

With a list comprehension you could write something like:

for index, row in enumerate([row for row in listSchedule if row[0] == 'Download']):
    row[3] = myOtherList[index]

Upvotes: 4

Related Questions