pythonic way to add elements to nested list

Viewed 101

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
4 Answers

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]

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]]

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

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))
Related