0

I have three lists, named list0, list1 and list2.
Here is what i want to do

for n in range(10):
    x = n%3
    listx.append(n)

where x can be 0, 1 or 2. How can I do this? Basically, I don't want to create 3 if/elif cases but just change the third line in above program

PS - I know this not the best method for this problem but my project is quite different from this

1
  • Why don't you make it a list of lists or a dictionary of lists? Then you can do list[x].append(n). Commented Dec 6, 2017 at 7:55

2 Answers 2

1

Why not a list of lists?

lists = [[],[],[]]
for n in range(10):
    list[n%3].append(n)

list1,list2,list3 = lists

or just use lists[i], which would scale better to bigger primes.

Sign up to request clarification or add additional context in comments.

Comments

0

If you insist, you can use locals() (or globals() to get your lists from the outer scope) to get your lists by name:

list0, list1, list2 = [], [], []

for n in range(10):
    x = n % 3
    locals()["list" + str(x)].append(n)

print(list0, list1, list2)  # [0, 3, 6, 9] [1, 4, 7] [2, 5, 8]

But that's really a bad practice.

1 Comment

Even worse practice if we're going there: eval("list"+str(x)+".append("+str(n)+")")

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.