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
Release: 2023-09-18 21:17:05
forward
835 people have browsed it

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)
Copy after login

Output

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

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)
Copy after login

Output

('Tuple = ', ('Tesla', 'Audi', 'Toyota'))
Copy after login

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"])
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template