Why does Python allow commas at the end of lists and tuples?


Python allow commas at the end of lists and tuples. It is optional and makes the items more readable and you can reorder the items without getting any error. You don’t need to remember again and again to add a trailing comma after every item, if you add a comma in the end.

Let’s see some examples −

Lists

Example

In this example, we will add a trailing comma in the List and there won’t be any error −

# Creating a List myList = ["Jacob", "Harry", "Mark", "Anthony", ] # Displaying the List print("List = ",myList)

Output

('List = ', ['Jacob', 'Harry', 'Mark', 'Anthony'])

Tuple

Example

In this example, we will add a trailing comma in the Tuple and there won’t be any error 

# Creating a Tuple myTuple = ("Tesla", "Audi", "Toyota",) # Displaying the Tuple print("Tuple = ",myTuple)

Output

('Tuple = ', ('Tesla', 'Audi', 'Toyota'))

Dictionary

Example

You can also add a trailing comma in a Dictionary 

# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes", } # Displaying the Dictionary print(myprod) # Displaying individual values print("Product = ",myprod["Product"]) print("Model = ",myprod["Model"]) print("Units = ",myprod["Units"]) print("Available = ",myprod["Available"])

Output

{'Units': 120, 'Available': 'Yes', 'Product': 'Mobile', 'Model': 'XUT'}
('Product = ', 'Mobile')
('Model = ', 'XUT')
('Units = ', 120)
('Available = ', 'Yes')

Updated on: 20-Sep-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements