Reputation: 1
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.
Upvotes: 0
Views: 8999
Reputation: 51
you have to declare the variables
a = []
# for list
a = ()
# for tuple
a = {}
# for dictionary
a = ""
# for an empty variable
Upvotes: 1
Reputation: 221
Python's syntax for declaring an empty list is names = []
, not names[]
. Once you've declared the list and put some items into it - e.g. 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.
Upvotes: 1
Reputation: 28987
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
Upvotes: 3
Reputation: 1484
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 = []
Upvotes: 2