Home > Software design >  How do you add Variables to lists in PyCharm?
How do you add Variables to lists in PyCharm?

Time:01-10

I am pretty new to Python, I'm using PyCharm using Python 3.9 I was wondering if anyone knew how to add user input variables to lists. I have tried .insert.append and It keeps giving me the same, "Name 'variable' can be undefined" error. If anyone has any knowledge on how to fix it, it would be greatly appreciated.

CodePudding user response:

The correct method is .append, it adds an element to the end of a list. You can also use .insert, which inserts that element at a certain index.

The warning "Name 'variable' can be undefined" is PyCharm's way of letting you know that the definition of the list you are trying to append to might not be executed.

For example, say you have the following code:

for a in somelist:
    someotherlist = ['a', 'b', 'c']
someotherlist.append('d')

You'd think this would always work, but what if somelist is empty? Then the for loop will never happen. So Python will try to append to a list that does not exist (someotherlist), which it cannot do.

So, make sure that the definition of the list you are trying to append to will always run before you try to append to it.

CodePudding user response:

In Python, you can create a empty list like this:

example_list = []

or

example_list = list()

To append elements to a list, you can use the append method of the list.

example_list.append( 'This is a list item' )

You can read more about the Python lists on the official documentation.

The error that you are getting basically says that, it can not find the variable by the name of 'variable'.

When asking a question on stack overflow, please provide the code in question, so we can assist you better. So go ahead and post the code, so we can help you better.

CodePudding user response:

If I am understanding your question correctly...

The input() command should give you the functionality you are wanting. The code simply runs through a loop and accepts user input at the beginning of each iteration. That input is then 'appended' to the current list using the append() method of the list object. If you are wanting to stop the loop then you would pass STOP

my_list = list()
STOP_STRING = 'STOP'
while True:
    value = input("Please Enter a value \n")
    if value == 'STOP':
        break
    my_list.append(value)

print(my_list)

Example output:

>>>Please Enter a value
>>>Hello
>>>Please Enter a value
>>>World
>>>Please Enter a value
>>>STOP
>>>['Hello', 'World']

  •  Tags:  
  • Related