简体   繁体   中英

Syntax Error when creating lists

I'm fairly new to Python and some small experience in programming. I searched other questions but am still not sure what to do. My basic problem is this: I downloaded Python Shell (3.5.2) and I get a syntax error whenever I try to enter "names[]", such as:

>>> names[]
SyntaxError: invalid syntax
>>>  

I don't know if I need to import some kind of library, or what I have to do and none of the other questions I've looked up answers something as basic as this. Any help would be appreciated.

You don't declare variables in Python. You just assign values to them. [] is an empty list.

>>> names = []

will create a variable called names and assign an empty list to it.

>>> names.append(1)

will append an integer with value 1 to it.

>>> names
[1]

Python values are strongly typed (you can't call append on an integer), but variables can be assigned new values at any time, and those values don't have to have the same type.

>>> names = 23
>>> names
23

The way you should use a list in python is :

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

or in your case, if you want an empty list, you could use :

list4 = list()
list5 = []

Python's syntax for declaring an empty list is names = [] , not names[] . Once you've declared the list and put some items into it - eg names.append('John Smith') - you can then access items in the list using the names[] syntax - names[0] for the first element in the list, for example.

If you're having this kind of trouble with basic language syntax, I strongly recommend working through some exercises in an online course that will introduce you to the basic principles of the language. The CodeAcademy python course is free and has been very helpful for a lot of people I work with who are light users of the language.

you have to declare the variables

a = [] # for list

a = () # for tuple

a = {} # for dictionary

a = "" # for an empty variable

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