0
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.

5
  • 3
    You could put all of your lists into another list and then iterate over it and add your item. Commented Oct 28, 2020 at 16:59
  • Whenever you have variables like x_1, x_2, ... of similar type and purpose, you should consider putting them in a list or other collection that allows dealing with them in bulk. Commented Oct 28, 2020 at 17:00
  • 3
    Having 20 lists, all managed independently, containing the same item feels lousy either way. Can you think of a better design? Commented Oct 28, 2020 at 17:01
  • y = lambda x: (list_1.append(x), list_2.append(x), list_2.append(x)) y(item_1) Commented Oct 28, 2020 at 17:03
  • perhaps there is a way of better designing, @DeepSpace, but I am a novice and at the moment, I don't see a better way... Commented Oct 28, 2020 at 17:05

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

The dict loop is a little off as it iterates the keys. Also list is a terrible variable name as it shadows the built-in type.
@Johnfishmaster thank you for your tip, but my project is complicated enough at the moment and like I said before, I am a novice and not so familiar with dictionaries.
Thats an extra reason to use them. Trying new things is part of learning. However you should only use this if are used for similar purposes anyway.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.