Home >Backend Development >Python Tutorial >Why does Python allow commas at the end of lists and tuples?

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

PHPz
PHPzforward
2023-09-18 21:17:05813browse

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 -

List

Example

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)

Output

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

Tuple

Example

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)

Output

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

dictionary

Example

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"])

Output

{'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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete