How create a empty list to python 3?

Viewed 114

What is the problem in this code, because I need create a empty list and I can't create a empty list.

def empty_list():
    empty_list=[]
    return empty_list
def text_to_list(the_text):
    empty_list=empty_list()
    empty_list[:0]=the_text
    return empty_list
# The print to show the result.
print(text_to_list("ABCD"))

The result:

Traceback (most recent call last):
  File "./prog.py", line 9, in <module>
  File "./prog.py", line 5, in text_to_list
UnboundLocalError: local variable 'empty_list' referenced before assignment
4 Answers

Simply

empty_list = []

will create an empty list that you can add to and call on

The issue is caused by the shared name between the variable and the function. Python checks for the variables created in the function before the function gets executed. At the time of the call, the interpreter already considers the empty_list a variable.

Solution Rename the function or the variable.

You don't really need functions to do this, but if you want to work with your code, make sure you don't use the same names for functions and variables. In your code, empty_list is used for almost everything which is confusing.

def empty_list():
    a_list=[]
    return a_list

def text_to_list(the_text):
    another_list = empty_list()
    another_list[:0] = the_text
    return another_list

# The print to show the result.
print(text_to_list("ABCD"))

As an aside, you can accomplish all of the above in one line as Python can easily convert strings to lists like so:

>>> list("ABCD")
['A', 'B', 'C', 'D']

A possible solution is calling the list() constructor, using it in a code would look something along the lines of

empty_list = list()

That will create an empty list.

Related