0

I'm new to python and just want to ask if it is possible to use def function to create new variables.

Here is my code, trying to build a function that i can input the variable name and data, it will automaticed output the different list. But it seems not working:

def Length5_list(list_name, a, b, c, d, e):
    list_name = list()
    list_name = [a, b, c, d, e]

list_name1 = 'first_list'
list_name2 = 'second_list'
A = 1
B = 2
C = 3
D = 4
E = 5

Length5_list(list_name1, A, B, C, D, E)
Length5_list(list_name2, E, D, C, B, A)

print(list_name1, list_name2)

Also wondering if there is any other way to achieve it?

Thank you guys soooo much!

1
  • Don't use dynamic variable names. It's almost always a poor design choice. Commented Jul 27, 2018 at 2:17

1 Answer 1

1

Do not name variables dynamically. Instead, use a dictionary and update it with items. Then retrieve your lists via d[key], where key is a string you have supplied to your function.

Here's an example:

def lister(list_name, a, b, c, d, e):
    return {list_name: [a, b, c, d, e]}

list_name1 = 'first_list'
list_name2 = 'second_list'
A, B, C, D, E = range(1, 6)

d = {}

d.update(lister(list_name1, A, B, C, D, E))
d.update(lister(list_name2, E, D, C, B, A))

print(d['first_list'], d['second_list'], sep='\n')

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

While there may be ways to create variables dynamically, it is not recommended. See How do I create a variable number of variables? for more details.

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

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.