Python Forum
Just need some clarification - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Just need some clarification (/thread-30042.html)



Just need some clarification - Tonje - Oct-01-2020

boston_celtics = ("kemba", "jaylen", "jayson")

second_player = (boston_celtics[1])

print("The second player in boston is %s" %second_player)
I stumbled upon this code and it piqued my interest. May I ask how this works?
Much thanks!!


RE: Just need some clarification - Marbelous - Oct-01-2020

It puts names (as strings) into a tuple, which is like a list or an array and names it boston_celtics.
Lists (and tuples) can be indexed by their position. Indexes are zero-based so the second name ("jaylen") can be indexed by boston_celtics[1].
The last line just prints it using a simple string formatting method and print statement.

All of this is explained in the short tutorial that comes with Python and is written by the creator of Python. It is also online here: https://docs.python.org/2.4/tut/tut.html


RE: Just need some clarification - buran - Oct-01-2020

@Marbelous, please don't share links to outdated tutorials. it's ancient (2.4) while latest py2 version is 2.7 and by now even python2 support ended
Here is the current one https://docs.python.org/3/tutorial/index.html

@Tonje - this is not best example of code
  • brackets on line 3 are redundant
    second_player = boston_celtics[1]
  • it uses so called old-style formatting. By now there is str.format() method and f-strings
    print("The second player in boston is {}".format(second_player))
    print(f"The second player in boston is {second_player}") # requires 3.6+



RE: Just need some clarification - deanhystad - Oct-01-2020

What is your confusion about the code? Are you wondering why boston_celtics[1] returns "jaylen" instead of "kemba"? Python indexing starts at 0, not 1.

Are you wondering what boston_celtics = ("kemba", "jaylen", "jayson") does? The () brackets are a way to create a collection called a tuple. Tuples are like lists (which use [] brackets) but they cannot be modified (append, remove or change items).

Are you wondering what print("The second player in boston is %s" %second_player) does?

print is a command that writes to standard output. What is written will appear in the terminal from which this program was run. The "%" is a format character. The % inside the quotes is replaced by the value of second_player when the string is printed. This is one of several variants of print formatting. I prefer using f strings which I think are easier to read: print(f'The second player in boston is {second_player}')