dan_from_d
dan_from_d

Reputation: 13

Append one item to multiple lists Python

item_1 = foo

list_1 = []
list_2 = []
list_3 = []

Is it possible to append item_1 to list_1, list_2 and list_3 in one line?

list_1.append(item_1)
list_2.append(item_1)
list_3.append(item_1)

seems very lousy to me; I have nearly 20 lists and I need one item in all of them.

Upvotes: 0

Views: 166

Answers (2)

John Janzen
John Janzen

Reputation: 88

Use loops:

lists_to_append_to = [list1,list2]
for list in lists_to_append_to:
     list.append(item_1)

if the names of the lists are really list_1,2 etc you should probably should a dictionary though:

lists = {
    1: list(),
    2: list()
}

In that case use the dictionary in the loop.

for current_list in lists:
     lists[current_list].append(item)

Upvotes: 1

E. Ducateme
E. Ducateme

Reputation: 4238

We can create a list of lists and use a for loop to iterate over all of them.

item_1 = 'foo'

list_1 = []
list_2 = []
list_3 = []

Here we create a list of lists (it can be any length):

mylist = [list_1, list_2, list_3]

Next we iterate over all the lists in the main list, one by one. Each list will be referenced by the target variable (in this case "l") and we can then call .append() on l.

for l in mylist:
    l.append(item_1)

To prove this works, we can then examine the main list and individual lists:

print(mylist)
[['foo'], ['foo'], ['foo']]

print(list_1)
['foo']

print(list_2)
['foo']

Upvotes: 0

Related Questions