Creating Lists
A List
in a document is useful for structuring information.
With python-docx, you can easily add ordered lists
and unordered lists
to a Word document.
In this lesson, we will learn how to create lists and style them in various ways.
Creating an Unordered List (Bullet List)
An unordered list displays items with bullet symbols (such as -, *, etc.) in front of each item.
This type of list is used when the items are independent of each other or when the order is not important.
In python-docx, an unordered list can be created using the add_paragraph()
method with the ListBullet
style.
Code Example
from docx import Document # Create a new Word document doc = Document() # Add unordered list items doc.add_paragraph('First item', style='ListBullet') doc.add_paragraph('Second item', style='ListBullet') doc.add_paragraph('Third item', style='ListBullet') # Save the document doc.save('output_file.docx')
-
add_paragraph('text', style='ListBullet')
adds a paragraph with bullet style applied. -
In the code above, 'First item', 'Second item', and 'Third item' are displayed as an unordered list with bullet points.
When you run this code, an unordered list with bullet symbols in front of each item will be created.
Creating an Ordered List (Numbered List)
An ordered list displays items with numbers in front of each item.
In python-docx, an ordered list can be created using the ListNumber
style.
Code Example
# Add ordered list items doc.add_paragraph('First item', style='ListNumber') doc.add_paragraph('Second item', style='ListNumber') doc.add_paragraph('Third item', style='ListNumber') # Save the document doc.save('output_file.docx')
-
add_paragraph('text', style='ListNumber')
adds a paragraph with number list style applied. -
In the code above, 'First item', 'Second item', and 'Third item' are displayed with numbers.
When you run this code, an ordered list with numbers in front of each item will be created.
Creating a Multi-level List
With python-docx, you can also create multi-level lists, which include sub-items.
This is done by using the same style while indenting paragraphs to represent hierarchy.
# Add multi-level list items doc.add_paragraph('Main item 1', style='ListNumber') doc.add_paragraph(' Sub-item 1.1', style='ListNumber') doc.add_paragraph(' Sub-item 1.2', style='ListNumber') doc.add_paragraph('Main item 2', style='ListNumber') doc.add_paragraph(' Sub-item 2.1', style='ListNumber') # Save the document doc.save('output_file.docx')
-
Indents are represented by adding spaces in front of paragraphs.
-
Main item 1
andMain item 2
include indented sub-items likeSub-item 1.1
andSub-item 1.2
.
When you run this code, a multi-level numbered list will be created.
What is the most appropriate style to fill in the blank below?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result
The document is empty.
Try running the code.