I just started in Python, working with ‘Python Crash Course’. Tried to run simplest code for bicycle list.
bicycle = ['trek ’ 'cannondale ’ 'redline ']
print(bicycle[0])
run
/python_working_lists.py
trek cannondale redline
Book says this should be
trek
What is keeping this from running correctly???
You need a comma between each element in the list.
When Python sees two strings next to each other without a comma, it concatenates them together, so what you get is the list bicycle = ['trek cannondale readline']
with one element
As per the above post.
For some very clear examples of that (as well as many more Python examples), you may find this to be of use:
What a silly mistake. And thanks so much for the quick reply. Well, I thought I copied it correctly.
Again, thanks
It happens.
An alternative (and possibly more “human readable”) way of constructing a list object is like this:
bicycle = [
"trek",
"cannondale",
"redline"
]
That way, the elements are easy to see and your code editor will (or should) indicate a syntax error, should you omit a comma.
Error correction: My thanks @cameron
Now there’s a thing: I can’t think why I thought it would (maybe from the Dictionary object syntax and my old head has its wires crossed) – I’ll “fact check” in future.
It happens.
Aye. All the time.
An alternative (and possibly more “human readable”) way of constructing a list object is like this:
bicycle = [ "trek", "cannondale", "redline" ]
That way, the elements are easy to see and your code editor will (or
should) indicate a syntax error, should you omit a comma.
Easier to read and easier to see mistakes. But it won’t provoke a syntax
error:
>>> bicycle = [
... "trek",
... "cannondale"
... "redline"
... ]
>>> bicycle
['trek', 'cannondaleredline']
Cheers,
Cameron Simpson cs@cskk.id.au