Home >Backend Development >Python Tutorial >Why does Python allow commas at the end of lists and tuples?
Python allows commas at the end of lists and tuples. It is optional, makes the project more readable, and you can reorder the projects without any errors. If you add a comma at the end, you don't have to remember again and again to add a trailing comma after each item.
Let’s look at some examples -
In this example we will add a trailing comma to the list so that we don’t get any errors -
# Creating a List myList = ["Jacob", "Harry", "Mark", "Anthony", ] # Displaying the List print("List = ",myList)
('List = ', ['Jacob', 'Harry', 'Mark', 'Anthony'])
In this example we will add a trailing comma in the tuple without any errors −
# Creating a Tuple myTuple = ("Tesla", "Audi", "Toyota",) # Displaying the Tuple print("Tuple = ",myTuple)
('Tuple = ', ('Tesla', 'Audi', 'Toyota'))
You can also add a trailing comma to the 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"])
{'Units': 120, 'Available': 'Yes', 'Product': 'Mobile', 'Model': 'XUT'} ('Product = ', 'Mobile') ('Model = ', 'XUT') ('Units = ', 120) ('Available = ', 'Yes')
The above is the detailed content of Why does Python allow commas at the end of lists and tuples?. For more information, please follow other related articles on the PHP Chinese website!