简体   繁体   中英

Python using def function to create defferent variables

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM