CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pylatex

A comprehensive Python library for programmatically creating and compiling LaTeX documents and snippets.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

lists.mddocs/

Lists and Enumerations

List environments including itemized lists, numbered lists, and description lists with customization options. PyLaTeX provides comprehensive support for LaTeX's list environments, enabling the creation of structured content with automatic numbering, custom symbols, and nested hierarchies.

Capabilities

Itemized Lists

The Itemize class creates bulleted lists with default or custom bullet symbols.

class Itemize(List):
    def __init__(self, *, options=None, **kwargs):
        """
        Create an itemized (bulleted) list.
        
        Parameters:
        - options: str, list, or Options, custom list options
        """
        
    def add_item(self, s):
        """
        Add an item to the list.
        
        Parameters:
        - s: str or LatexObject, the item content
        """

Usage example:

from pylatex import Document, Section
from pylatex.lists import Itemize

doc = Document()

with doc.create(Section('Project Requirements')):
    with doc.create(Itemize()) as itemize:
        itemize.add_item('User authentication system')
        itemize.add_item('Database integration')
        itemize.add_item('RESTful API endpoints')
        itemize.add_item('Frontend user interface')
        itemize.add_item('Comprehensive testing suite')

# Nested lists
with doc.create(Section('Technical Stack')):
    with doc.create(Itemize()) as itemize:
        itemize.add_item('Backend Technologies')
        
        # Nested list
        with itemize.create(Itemize()) as nested:
            nested.add_item('Python 3.8+')
            nested.add_item('Django framework')
            nested.add_item('PostgreSQL database')
        
        itemize.add_item('Frontend Technologies')
        
        with itemize.create(Itemize()) as nested:
            nested.add_item('React.js')
            nested.add_item('TypeScript')
            nested.add_item('CSS3 with Flexbox')

Enumerated Lists

The Enumerate class creates numbered lists with support for custom numbering schemes and styles.

class Enumerate(List):
    def __init__(self, enumeration_symbol=None, *, options=None, **kwargs):
        """
        Create an enumerated (numbered) list.
        
        Parameters:
        - enumeration_symbol: str, custom enumeration symbol pattern
        - options: str, list, or Options, custom list options
        
        Requires:
        - enumitem package (automatically added when using enumeration_symbol)
        """
        
    def add_item(self, s):
        """
        Add an item to the enumerated list.
        
        Parameters:
        - s: str or LatexObject, the item content
        """

Usage example:

from pylatex import Document, Section, NoEscape
from pylatex.lists import Enumerate

doc = Document()

with doc.create(Section('Implementation Steps')):
    # Basic numbered list
    with doc.create(Enumerate()) as enum:
        enum.add_item('Design system architecture')
        enum.add_item('Set up development environment')
        enum.add_item('Implement core functionality')
        enum.add_item('Write comprehensive tests')
        enum.add_item('Deploy to production')

# Custom numbering styles
with doc.create(Section('Custom Numbering')):
    # Roman numerals
    with doc.create(Enumerate(enumeration_symbol=NoEscape(r'\roman*'))) as enum:
        enum.add_item('First phase')
        enum.add_item('Second phase')
        enum.add_item('Third phase')
    
    # Alphabetical
    with doc.create(Enumerate(enumeration_symbol=NoEscape(r'\alph*)'))) as enum:
        enum.add_item('Primary objective')
        enum.add_item('Secondary objective')
        enum.add_item('Tertiary objective')
    
    # Custom format
    with doc.create(Enumerate(enumeration_symbol=NoEscape(r'Step \arabic*:'))) as enum:
        enum.add_item('Initialize variables')
        enum.add_item('Process input data')
        enum.add_item('Generate output')

# Nested enumerated lists
with doc.create(Section('Detailed Workflow')):
    with doc.create(Enumerate()) as enum:
        enum.add_item('Data Collection')
        
        with enum.create(Enumerate(enumeration_symbol=NoEscape(r'\alph*)'))) as subenum:
            subenum.add_item('Survey participants')
            subenum.add_item('Gather measurements')
            subenum.add_item('Record observations')
        
        enum.add_item('Data Analysis')
        
        with enum.create(Enumerate(enumeration_symbol=NoEscape(r'\alph*)'))) as subenum:
            subenum.add_item('Statistical processing')
            subenum.add_item('Visualization')
            subenum.add_item('Interpretation')

Description Lists

The Description class creates definition-style lists with terms and their descriptions.

class Description(List):
    def __init__(self, *, options=None, **kwargs):
        """
        Create a description list.
        
        Parameters:
        - options: str, list, or Options, custom list options
        """
        
    def add_item(self, label, s):
        """
        Add an item to the description list.
        
        Parameters:
        - label: str, the term or label to define
        - s: str or LatexObject, the description content
        """

Usage example:

from pylatex import Document, Section, Command
from pylatex.lists import Description

doc = Document()

with doc.create(Section('Terminology')):
    with doc.create(Description()) as desc:
        desc.add_item('API', 'Application Programming Interface - a set of protocols and tools for building software applications')
        desc.add_item('REST', 'Representational State Transfer - an architectural style for distributed hypermedia systems')
        desc.add_item('CRUD', 'Create, Read, Update, Delete - the four basic operations of persistent storage')
        desc.add_item('ORM', 'Object-Relational Mapping - programming technique for converting data between incompatible type systems')

# Enhanced formatting
with doc.create(Section('Technical Specifications')):
    with doc.create(Description()) as desc:
        desc.add_item(
            Command('textbf', 'Python'), 
            'High-level programming language with dynamic semantics and extensive standard library'
        )
        desc.add_item(
            Command('textbf', 'Django'), 
            'Web framework that encourages rapid development and clean, pragmatic design'
        )
        desc.add_item(
            Command('textbf', 'PostgreSQL'), 
            'Open-source relational database system with strong reputation for reliability and performance'
        )

Advanced List Features

Custom List Styling

from pylatex import Document, Section, Package, NoEscape
from pylatex.lists import Itemize, Enumerate
from pylatex.base_classes import Options

doc = Document()

# Add enumitem package for advanced customization
doc.packages.append(Package('enumitem'))

with doc.create(Section('Custom Styled Lists')):
    # Custom bullet symbols
    custom_options = Options()
    custom_options.append(NoEscape(r'label=\textbullet'))
    
    with doc.create(Itemize(options=custom_options)) as itemize:
        itemize.add_item('Custom bullet point')
        itemize.add_item('Another bullet point')
    
    # Compact spacing
    compact_options = Options()
    compact_options.append(NoEscape('nosep'))
    
    with doc.create(Enumerate(options=compact_options)) as enum:
        enum.add_item('Tight spacing item 1')
        enum.add_item('Tight spacing item 2')
        enum.add_item('Tight spacing item 3')
    
    # Custom indentation
    indent_options = Options()
    indent_options.append(NoEscape('leftmargin=2cm'))
    indent_options.append(NoEscape('itemindent=1cm'))
    
    with doc.create(Itemize(options=indent_options)) as itemize:
        itemize.add_item('Custom indented item')
        itemize.add_item('Another indented item')

Multi-Level Lists

from pylatex import Document, Section, NoEscape
from pylatex.lists import Enumerate, Itemize

doc = Document()

with doc.create(Section('Project Hierarchy')):
    with doc.create(Enumerate()) as main_list:
        main_list.add_item('Frontend Development')
        
        with main_list.create(Itemize()) as sub_items:
            sub_items.add_item('Component Architecture')
            
            with sub_items.create(Enumerate(enumeration_symbol=NoEscape(r'\alph*)'))) as subsub:
                subsub.add_item('Header component')
                subsub.add_item('Navigation component')
                subsub.add_item('Footer component')
            
            sub_items.add_item('State Management')
            sub_items.add_item('Routing System')
        
        main_list.add_item('Backend Development')
        
        with main_list.create(Itemize()) as sub_items:
            sub_items.add_item('Database Design')
            sub_items.add_item('API Endpoints')
            sub_items.add_item('Authentication')
        
        main_list.add_item('Testing Strategy')

Mixed Content Lists

from pylatex import Document, Section, Command, NoEscape
from pylatex.lists import Enumerate, Description
from pylatex.math import Math

doc = Document()

with doc.create(Section('Mathematical Concepts')):
    with doc.create(Description()) as desc:
        # List items with mathematical content
        desc.add_item(
            'Quadratic Formula',
            Math(data=NoEscape(r'x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}'), inline=True)
        )
        
        desc.add_item(
            'Pythagorean Theorem', 
            ['For a right triangle: ', Math(data=NoEscape(r'a^2 + b^2 = c^2'), inline=True)]
        )
        
        desc.add_item(
            Command('textit', 'Euler\'s Identity'),
            Math(data=NoEscape(r'e^{i\pi} + 1 = 0'), inline=True)
        )

# Code examples in lists
with doc.create(Section('Programming Examples')):
    with doc.create(Enumerate()) as enum:
        enum.add_item([
            'Variable declaration: ',
            NoEscape(r'\texttt{x = 10}')
        ])
        enum.add_item([
            'Function definition: ',
            NoEscape(r'\texttt{def func(param):}')
        ])
        enum.add_item([
            'Class instantiation: ',
            NoEscape(r'\texttt{obj = MyClass()}')
        ])

List Formatting and Styling

Spacing and Layout Control

from pylatex import Document, Package, Command, NoEscape
from pylatex.lists import Itemize, Enumerate
from pylatex.base_classes import Options

doc = Document()
doc.packages.append(Package('enumitem'))

# Global list settings
doc.preamble.append(Command('setlist', options='itemsep=0.5em,parsep=0pt,partopsep=0pt'))

with doc.create(Section('Controlled Spacing')):
    # No extra spacing
    tight_options = Options(['noitemsep', 'topsep=0pt', 'parsep=0pt'])
    
    with doc.create(Itemize(options=tight_options)) as itemize:
        itemize.add_item('Compact item 1')
        itemize.add_item('Compact item 2')
        itemize.add_item('Compact item 3')
    
    # Extra spacing
    spaced_options = Options(['itemsep=1em', 'topsep=1em'])
    
    with doc.create(Enumerate(options=spaced_options)) as enum:
        enum.add_item('Spaced item 1')
        enum.add_item('Spaced item 2')
        enum.add_item('Spaced item 3')

Custom Symbols and Numbering

from pylatex import Document, Section, Package, NoEscape, Command
from pylatex.lists import Itemize, Enumerate

doc = Document()
doc.packages.append(Package('enumitem'))
doc.packages.append(Package('pifont'))  # For special symbols

with doc.create(Section('Custom Symbols')):
    # Special bullet symbols
    with doc.create(Itemize(enumeration_symbol=NoEscape(r'\ding{43}'))) as itemize:
        itemize.add_item('Star bullet point')
        itemize.add_item('Another star point')
    
    # Arrow bullets
    with doc.create(Itemize(enumeration_symbol=NoEscape(r'$\rightarrow$'))) as itemize:
        itemize.add_item('Arrow bullet point')
        itemize.add_item('Another arrow point')
    
    # Custom numbering with prefixes/suffixes
    with doc.create(Enumerate(enumeration_symbol=NoEscape(r'Task \arabic*:'))) as enum:
        enum.add_item('Complete requirements analysis')
        enum.add_item('Design system architecture')
        enum.add_item('Implement core features')

Continuation and Resuming

from pylatex import Document, Section, NoEscape
from pylatex.lists import Enumerate
from pylatex.base_classes import Options

doc = Document()

with doc.create(Section('Continuing Lists')):
    # First part of list
    with doc.create(Enumerate()) as enum:
        enum.add_item('First item')
        enum.add_item('Second item')
        enum.add_item('Third item')
    
    doc.append('Some intervening text that breaks the list.')
    
    # Resume numbering
    resume_options = Options(['resume'])
    
    with doc.create(Enumerate(options=resume_options)) as enum:
        enum.add_item('Fourth item (continued)')
        enum.add_item('Fifth item (continued)')

Practical List Applications

Task Lists and Checklists

from pylatex import Document, Section, Package, NoEscape
from pylatex.lists import Itemize

doc = Document()
doc.packages.append(Package('amssymb'))  # For checkboxes

with doc.create(Section('Project Checklist')):
    checkboxes = [
        (NoEscape(r'$\boxtimes$'), 'Requirements gathering', 'completed'),
        (NoEscape(r'$\boxtimes$'), 'System design', 'completed'),  
        (NoEscape(r'$\square$'), 'Implementation', 'pending'),
        (NoEscape(r'$\square$'), 'Testing', 'pending'),
        (NoEscape(r'$\square$'), 'Deployment', 'pending')
    ]
    
    with doc.create(Itemize()) as itemize:
        for checkbox, task, status in checkboxes:
            itemize.add_item([checkbox, ' ', task])

Bibliography-Style Lists

from pylatex import Document, Section, Command
from pylatex.lists import Description

doc = Document()

with doc.create(Section('References')):
    with doc.create(Description()) as desc:
        desc.add_item(
            '[1]',
            'Smith, J. (2023). "Advanced LaTeX Techniques." '
            + Command('textit', 'Journal of Document Processing') + ', 15(3), 123-145.'
        )
        desc.add_item(
            '[2]',
            'Johnson, A. & Brown, B. (2022). "Python for Scientific Writing." '
            + 'Academic Press, New York.'
        )
        desc.add_item(
            '[3]',
            'Davis, C. (2024). "Automated Document Generation." '
            + 'Proceedings of the International Conference on Documentation.'
        )

Feature Comparison Lists

from pylatex import Document, Section, Command
from pylatex.lists import Description
from pylatex.table import Tabular

doc = Document()

with doc.create(Section('Feature Comparison')):
    with doc.create(Description()) as desc:
        desc.add_item(
            Command('textbf', 'Basic Plan'),
            'Up to 5 users, 10GB storage, email support'
        )
        desc.add_item(
            Command('textbf', 'Professional Plan'),
            'Up to 25 users, 100GB storage, priority support, advanced analytics'
        )
        desc.add_item(
            Command('textbf', 'Enterprise Plan'),
            'Unlimited users, 1TB storage, dedicated support, custom integrations'
        )

Error Handling and Best Practices

Empty List Handling

Lists in PyLaTeX automatically handle empty content through the omit_if_empty attribute:

from pylatex.lists import Itemize

# This will not produce LaTeX output if no items are added
empty_list = Itemize()
# empty_list.add_item()  # No items added

# This ensures the list appears in output
non_empty_list = Itemize()
non_empty_list.add_item('At least one item')

Package Requirements

Different list features require specific packages:

  • Basic lists: No additional packages
  • Custom enumeration: enumitem package (automatically added)
  • Special symbols: pifont, amssymb, or textcomp packages
  • Unicode symbols: May require fontspec with XeLaTeX or LuaLaTeX
from pylatex import Document, Package

doc = Document()
doc.packages.append(Package('enumitem'))
doc.packages.append(Package('pifont'))
doc.packages.append(Package('amssymb'))

The list system in PyLaTeX provides flexible and powerful tools for creating structured content with professional formatting and extensive customization options.

Install with Tessl CLI

npx tessl i tessl/pypi-pylatex

docs

base-classes.md

configuration.md

document.md

figures.md

index.md

layout.md

lists.md

math.md

quantities.md

references.md

sectioning.md

tables.md

text-formatting.md

tikz.md

utilities.md

tile.json