100% found this document useful (1 vote)
16 views

Introduction to Python for Econometrics, Statistics and Data Analysis. 5th Edition Kevin Sheppard. instant download

Ebook

Uploaded by

laurysrafath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
16 views

Introduction to Python for Econometrics, Statistics and Data Analysis. 5th Edition Kevin Sheppard. instant download

Ebook

Uploaded by

laurysrafath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Introduction to Python for Econometrics,

Statistics and Data Analysis. 5th Edition Kevin


Sheppard. install download

https://ebookmeta.com/product/introduction-to-python-for-
econometrics-statistics-and-data-analysis-5th-edition-kevin-
sheppard/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Statistics for Data Scientists: An Introduction to


Probability, Statistics, and Data Analysis Maurits
Kaptein

https://ebookmeta.com/product/statistics-for-data-scientists-an-
introduction-to-probability-statistics-and-data-analysis-maurits-
kaptein/

Introduction to Statistics and Data Analysis, 6th


Edition Peck

https://ebookmeta.com/product/introduction-to-statistics-and-
data-analysis-6th-edition-peck/

Introduction to Python in Earth Science Data Analysis


1st Edition Maurizio Petrelli

https://ebookmeta.com/product/introduction-to-python-in-earth-
science-data-analysis-1st-edition-maurizio-petrelli/

Social Media Marketing A Strategic Approach 2nd Edition


Melissa Barker

https://ebookmeta.com/product/social-media-marketing-a-strategic-
approach-2nd-edition-melissa-barker/
Essentials of Economics, 10e 10th Edition N. Gregory
Mankiw

https://ebookmeta.com/product/essentials-of-economics-10e-10th-
edition-n-gregory-mankiw/

Beginning Windows Mixed Reality Programming: For


HoloLens and Mixed Reality Headsets, 2nd Edition Sean
Ong

https://ebookmeta.com/product/beginning-windows-mixed-reality-
programming-for-hololens-and-mixed-reality-headsets-2nd-edition-
sean-ong/

An Introduction to Economic Dynamics: Modelling,


Analysis and Simulation 1st Edition Srinivas
Raghavendra

https://ebookmeta.com/product/an-introduction-to-economic-
dynamics-modelling-analysis-and-simulation-1st-edition-srinivas-
raghavendra/

Pokemon HeartGold SoulSilver The Official Pokemon Kanto


Guide National Pokedex Official Strategy Guide Prima
Official Game Guide The Pokemon Company

https://ebookmeta.com/product/pokemon-heartgold-soulsilver-the-
official-pokemon-kanto-guide-national-pokedex-official-strategy-
guide-prima-official-game-guide-the-pokemon-company/

Become a Competent Music Producer in 365 Days 1st


Edition Sam George

https://ebookmeta.com/product/become-a-competent-music-producer-
in-365-days-1st-edition-sam-george/
The Legal Effects of Recognition in International Law:
As Interpreted by the Courts of the United States John
G. Hervey

https://ebookmeta.com/product/the-legal-effects-of-recognition-
in-international-law-as-interpreted-by-the-courts-of-the-united-
states-john-g-hervey/
Introduction to Python for
Econometrics, Statistics and Data Analysis
5th Edition

Kevin Sheppard
University of Oxford

Monday 27th September, 2021


2

©2020 Kevin Sheppard


Notes to the 5th Edition

• Python 3.8 or 3.9 are the recommended versions.

• Added a chapter Code Style.

• Expanded coverage of random number generation and added coverage of the preferred method to gener-
ate random variates, numpy.random.Generator in chapter Simulating Random Variables.

• Verified that all code and examples work correctly against 2020 versions of modules. The notable pack-
ages and their versions are:

– Python 3.9 (Preferred version), 3.7 (Minimum version)


– NumPy: 1.20.3
– SciPy: 1.7.1
– pandas: 1.3.2
– matplotlib: 3.4.2
– statsmodels: 0.13.0
ii
Notes to the 4th Edition

• Python 3.8 is the recommended version. The notes require Python 3.6 or later, and all references to
Python 2.7 have been removed.
• Removed references to NumPy’s matrix class and clarified that it should not be used.
• Verified that all code and examples work correctly against 2020 versions of modules. The notable pack-
ages and their versions are:
– Python 3.8 (Preferred version), 3.6 (Minimum version)
– NumPy: 1.19.1
– SciPy: 1.5.2
– pandas: 1.1.1
– matplotlib: 3.3.1
• Introduced f-Strings in Section 23.3.3 as the preferred way to format strings using modern Python. The
notes use f-String where possible instead of format.
• Added coverage of Windowing function – rolling, expanding and ewm – to the pandas chapter.
• Expanded the list of packages of interest to researchers working in statistics, econometrics and machine
learning.
• Expanded description of model classes and statistical tests in statsmodels that are most relevant for econo-
metrics. Added section detailing formula support. This list represents on a small function of the statsmod-
els API.
• Added minimize as the preferred interface for non-linear function optimization in Chapter 22.
• Python 2.7 support has been officially dropped, although most examples continue to work with 2.7. Do
not Python 2.7 for numerical code.
• Small typo fixes, thanks to Marton Huebler.
• Fixed direct download of FRED data due to API changes, thanks to Jesper Termansen.
• Thanks for Bill Tubbs for a detailed read and multiple typo reports.
• Updated to changes in line profiler (see Ch. 25)
• Updated deprecations in pandas.
• Removed hold from plotting chapter since this is no longer required.
• Thanks for Gen Li for multiple typo reports.
iv
Notes to the 3rd Edition

This edition includes the following changes from the second edition (August 2014):

• Rewritten installation section focused exclusively on using Continuum’s Anaconda.

• Python 3.5 is the default version of Python instead of 2.7. Python 3.5 (or newer) is well supported by
the Python packages required to analyze data and perform statistical analysis, and bring some new useful
features, such as a new operator for matrix multiplication (@).

• Removed distinction between integers and longs in built-in data types chapter. This distinction is only
relevant for Python 2.7.

• dot has been removed from most examples and replaced with @ to produce more readable code.

• Split Cython and Numba into separate chapters to highlight the improved capabilities of Numba.

• Verified all code working on current versions of core libraries using Python 3.5.

• pandas

– Updated syntax of pandas functions such as resample.


– Added pandas Categorical.
– Expanded coverage of pandas groupby.
– Expanded coverage of date and time data types and functions.

• New chapter introducing statsmodels, a package that facilitates statistical analysis of data. statsmodels
includes regression analysis, Generalized Linear Models (GLM) and time-series analysis using ARIMA
models.
vi
Changes since the Second Edition

• Fixed typos reported by a reader – thanks to Ilya Sorvachev

• Code verified against Anaconda 2.0.1.

• Added diagnostic tools and a simple method to use external code in the Cython section.

• Updated the Numba section to reflect recent changes.

• Fixed some typos in the chapter on Performance and Optimization.

• Added examples of joblib and IPython’s cluster to the chapter on running code in parallel.

• New chapter introducing object-oriented programming as a method to provide structure and organization
to related code.

• Added seaborn to the recommended package list, and have included it be default in the graphics chapter.

• Based on experience teaching Python to economics students, the recommended installation has been
simplified by removing the suggestion to use virtual environment. The discussion of virtual environments
as been moved to the appendix.

• Rewrote parts of the pandas chapter.

• Changed the Anaconda install to use both create and install, which shows how to install additional pack-
ages.

• Fixed some missing packages in the direct install.

• Changed the configuration of IPython to reflect best practices.

• Added subsection covering IPython profiles.

• Small section about Spyder as a good starting IDE.


viii
Notes to the 2nd Edition

This edition includes the following changes from the first edition (March 2012):

• The preferred installation method is now Continuum Analytics’ Anaconda. Anaconda is a complete
scientific stack and is available for all major platforms.

• New chapter on pandas. pandas provides a simple but powerful tool to manage data and perform prelim-
inary analysis. It also greatly simplifies importing and exporting data.

• New chapter on advanced selection of elements from an array.

• Numba provides just-in-time compilation for numeric Python code which often produces large perfor-
mance gains when pure NumPy solutions are not available (e.g. looping code).

• Dictionary, set and tuple comprehensions

• Numerous typos

• All code has been verified working against Anaconda 1.7.0.


x
Contents

1 Introduction 1
1.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Important Components of the Python Scientific Stack . . . . . . . . . . . . . . . . . . . . . 3
1.4 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Using Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.A Additional Installation Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Built-in Data Types 15


2.1 Variable Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Core Native Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Additional Container Data Types in the Standard Library . . . . . . . . . . . . . . . . . . . 24
2.4 Python and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

3 Arrays 29
3.1 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2 1-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.3 2-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6 Accessing Elements of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.7 Slicing and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.8 import and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.9 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

4 Basic Math 43
4.1 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2 Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3 Addition (+) and Subtraction (-) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.4 Multiplication (⁎) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.5 Matrix Multiplication (@) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6 Array and Matrix Division (/) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
xii CONTENTS

4.7 Exponentiation (**) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46


4.8 Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.9 Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.10 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

5 Basic Functions and Numerical Indexing 49


5.1 Generating Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.2 Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.4 Complex Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5 Set Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.6 Sorting and Extreme Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.7 Nan Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.8 Functions and Methods/Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

6 Special Arrays 61
6.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

7 Array Functions 63
7.1 Shape Information and Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
7.2 Linear Algebra Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.3 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

8 Importing and Exporting Data 75


8.1 Importing Data using pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.2 Importing Data without pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
8.3 Saving or Exporting Data using pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.4 Saving or Exporting Data without pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

9 Inf, NaN and Numeric Limits 83


9.1 inf and NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
9.2 Floating point precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
9.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

10 Logical Operators and Find 85


10.1 >, >=, <, <=, ==, != . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
10.2 and, or, not and xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
10.3 Multiple tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
10.4 is⁎ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
10.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
CONTENTS xiii

11 Advanced Selection and Assignment 91


11.1 Numerical Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
11.2 Logical Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
11.3 Performance Considerations and Memory Management . . . . . . . . . . . . . . . . . . . 99
11.4 Assignment with Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
11.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

12 Flow Control, Loops and Exception Handling 103


12.1 Whitespace and Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
12.2 if . . . elif . . . else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
12.3 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
12.4 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
12.5 try . . . except . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
12.6 List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
12.7 Tuple, Dictionary and Set Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . 110
12.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

13 Code Style 113


13.1 PEP8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
13.2 black . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
13.3 isort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
13.4 flake8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
13.5 pylint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

14 Dates and Times 119


14.1 Creating Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
14.2 Dates Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
14.3 Output Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
14.4 Numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
14.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

15 Graphics 125
15.1 seaborn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
15.2 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
15.3 Advanced 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
15.4 3D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
15.5 General Plotting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
15.6 Exporting Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
15.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

16 pandas 145
16.1 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
16.2 Statistical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
16.3 Time-series Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
16.4 Importing and Exporting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
xiv CONTENTS

16.5 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177


16.6 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
16.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

17 Structured Arrays 187


17.1 Mixed Arrays with Column Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
17.2 Record Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

18 Custom Function and Modules 191


18.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
18.2 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
18.3 Example: Least Squares with Newey-West Covariance . . . . . . . . . . . . . . . . . . . . 198
18.4 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
18.5 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
18.6 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
18.7 PYTHONPATH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
18.8 Python Coding Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
18.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
18.A Listing of econometrics.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

19 Probability and Statistical Functions 207


19.1 Statistics Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
19.2 Continuous Random Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.3 Select Statistics Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
19.4 Select Statistical Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
19.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

20 Simulating Random Variables 217


20.1 Generating Random Variates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
20.2 Legacy Generation using RandomState . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
20.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

21 Statistical Analysis with statsmodels 229


21.1 Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
21.2 Generalized Linear Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
21.3 Other Notable Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.4 Time-series Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

22 Non-linear Function Optimization 237


22.1 Unconstrained Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
22.2 Derivative-free Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
22.3 Constrained Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
22.4 Scalar Function Minimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
22.5 minimize: Unified Interface for Function Minimization . . . . . . . . . . . . . . . . . . . 246
22.6 Nonlinear Least Squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
CONTENTS xv

22.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

23 String Manipulation 249


23.1 String Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
23.2 String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
23.3 Formatting Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
23.4 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
23.5 Safe Conversion of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

24 File System Operations 261


24.1 Changing the Working Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
24.2 Creating and Deleting Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
24.3 Listing the Contents of a Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
24.4 Copying, Moving and Deleting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
24.5 Executing Other Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
24.6 Creating and Opening Archives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
24.7 Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
24.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

25 Performance and Code Optimization 267


25.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
25.2 Timing Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
25.3 Vectorize to Avoid Unnecessary Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
25.4 Alter the loop dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
25.5 Utilize Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
25.6 Use In-place Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
25.7 Avoid Allocating Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
25.8 Inline Frequent Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
25.9 Consider Data Locality in Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
25.10Profile Long Running Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

26 Improving Performance using Numba 275


26.1 Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
26.2 Supported Python Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
26.3 Supported NumPy Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
26.4 Diagnosing Performance Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
26.5 Replacing Python function with C functions . . . . . . . . . . . . . . . . . . . . . . . . . . 285
26.6 Other Features of Numba . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

27 Improving Performance using Cython 289


27.1 Diagnosing Performance Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
27.2 Interfacing with External Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
27.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
xvi CONTENTS

28 Executing Code in Parallel 303


28.1 map and related functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
28.2 multiprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
28.3 joblib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
28.4 IPython’s Parallel Cluster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
28.5 Converting a Serial Program to Parallel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
28.6 Other Concerns when executing in Parallel . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

29 Object-Oriented Programming (OOP) 317


29.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
29.2 Class basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
29.3 Building a class for Autoregressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
29.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326

30 Other Interesting Python Packages 327


30.1 Statistics and Statistical Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
30.2 Machine Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
30.3 Deep Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
30.4 Other Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329

31 Examples 331
31.1 Estimating the Parameters of a GARCH Model . . . . . . . . . . . . . . . . . . . . . . . . 331
31.2 Estimating the Risk Premia using Fama-MacBeth Regressions . . . . . . . . . . . . . . . . 335
31.3 Estimating the Risk Premia using GMM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
31.4 Outputting LATEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341

32 Quick Reference 345


32.1 Built-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
32.2 NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
32.3 SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
32.4 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
32.5 pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
32.6 IPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Chapter 1

Introduction

1.1 Background
These notes are designed for someone new to statistical computing wishing to develop a set of skills necessary
to perform original research using Python. They should also be useful for students, researchers or practition-
ers who require a versatile platform for econometrics, statistics or general numerical analysis (e.g. numeric
solutions to economic models or model simulation).
Python is a popular general–purpose programming language that is well suited to a wide range of problems.1
Recent developments have extended Python’s range of applicability to econometrics, statistics, and general
numerical analysis. Python – with the right set of add-ons – is comparable to domain-specific languages such
as R, MATLAB or Julia. If you are wondering whether you should bother with Python (or another language),
an incomplete list of considerations includes:
You might want to consider R if:

• You want to apply statistical methods. The statistics library of R is second to none, and R is clearly at the
forefront of new statistical algorithm development – meaning you are most likely to find that new(ish)
procedure in R.

• Performance is of secondary importance.

• Free is important.

You might want to consider MATLAB if:

• Commercial support and a clear channel to report issues is important.

• Documentation and organization of modules are more important than the breadth of algorithms available.

• Performance is an important concern. MATLAB has optimizations, such as Just-in-Time (JIT) compila-
tion of loops, which is not automatically available in most other packages.

You might want to consider Julia if:

• Performance in an interactive based language is your most important concern.

• You don’t mind learning enough Python to interface with Python packages. The Julia ecosystem is less
complete than Python and a bridge to Python is used to provide missing features.
1
According to the ranking on http://www.tiobe.com/tiobe-index/, Python is the 5th most popular language. http:
//langpop.corger.nl/ ranks Python as 4th or 5th .
2 Introduction

• You like to do most things yourself or you are on the bleeding edge and so existing libraries do not exist
with the features you require.

Having read the reasons to choose another package, you may wonder why you should consider Python.

• You need a language which can act as an end-to-end solution that allows access to web-based services,
database servers, data management and processing and statistical computation. Python can even be used
to write server-side apps such as a dynamic website (see e.g. http://stackoverflow.com), apps
for desktop-class operating systems with graphical user interfaces, or apps for tablets and phones apps
(iOS and Android).

• Data handling and manipulation – especially cleaning and reformatting – is an important concern. Python
is substantially more capable at data set construction than either R or MATLAB.

• Performance is a concern, but not at the top of the list.2

• Free is an important consideration – Python can be freely deployed, even to 100s of servers in on a
cloud-based cluster (e.g. Amazon Web Services, Google Compute or Azure).

• Knowledge of Python, as a general purpose language, is complementary to R/MATLAB/Julia/Ox/-


GAUSS/Stata.

1.2 Conventions
These notes will follow two conventions.

1. Code blocks will be used throughout.


"""A docstring
"""

# Comments appear in a different color

# Reserved keywords are highlighted


and as assert break class continue def del elif else
except exec finally for from global if import in is
lambda not or pass print raise return try while with yield

# Common functions and classes are highlighted in a


# different color. Note that these are not reserved,
# and can be used although best practice would be
# to avoid them if possible
array range list True False None

# Long lines are indented


some_text = 'This is a very, very, very, very, very, very, very, very, very, very,
very, very long line.'

2. When a code block contains >>>, this indicates that the command is running an interactive IPython
session. Output will often appear after the console command, and will not be preceded by a command
indicator.
2
Python performance can be made arbitrarily close to C using a variety of methods, including numba (pure python), Cython
(C/Python creole language) or directly calling C code. Moreover, recent advances have substantially closed the gap with respect to
other Just-in-Time compiled languages such as MATLAB.
1.3 Important Components of the Python Scientific Stack 3

>>> x = 1.0
>>> x + 2
3.0

If the code block does not contain the console session indicator, the code contained in the block is
intended to be executed in a standalone Python file.
import numpy as np

x = np.array([1,2,3,4])
y = np.sum(x)
print(x)
print(y)

1.3 Important Components of the Python Scientific Stack


1.3.1 Python
Python 3.6 (or later) is required, and Python 3.8 (the latest release) is recommended. This provides the core
Python interpreter.

1.3.2 NumPy
NumPy provides a set of array data types which are essential for statistics, econometrics and data analysis.

1.3.3 SciPy
SciPy contains a large number of routines needed for analysis of data. The most important include a wide range
of random number generators, linear algebra routines, and optimizers. SciPy depends on NumPy.

1.3.4 Jupyter and IPython


IPython provides an interactive Python environment which enhances productivity when developing code or
performing interactive data analysis. Jupyter provides a generic set of infrastructure that enables IPython to be
run in a variety of settings including an improved console (QtConsole) or in an interactive web-browser based
notebook.

1.3.5 matplotlib and seaborn


matplotlib provides a plotting environment for 2D plots, with limited support for 3D plotting. seaborn is a
Python package that improves the default appearance of matplotlib plots without any additional code.

1.3.6 pandas
pandas provides high-performance data structures and is essential when working with data.

1.3.7 statsmodels
statsmodels is pandas-aware and provides models used in the statistical analysis of data including linear regres-
sion, Generalized Linear Models (GLMs), and time-series models (e.g., ARIMA).
4 Introduction

1.3.8 Performance Modules


A number of modules are available to help with performance. These include Cython and Numba. Cython is a
Python module which facilitates using a Python-like language to write functions that can be compiled to native
(C code) Python extensions. Numba uses a method of just-in-time compilation to translate a subset of Python
to native code using Low-Level Virtual Machine (LLVM).

1.4 Setup
The recommended method to install the Python scientific stack is to use Continuum Analytics’ Anaconda.
Appendix ?? describes a more complex installation procedure with instructions for directly installing Python
and the required modules when it is not possible to install Anaconda.

Continuum Analytics’ Anaconda


Anaconda, a free product of Continuum Analytics (www.continuum.io), is a virtually complete scientific
stack for Python. It includes both the core Python interpreter and standard libraries as well as most modules
required for data analysis. Anaconda is free to use and modules for accelerating the performance of linear alge-
bra on Intel processors using the Math Kernel Library (MKL) are provided. Continuum Analytics also provides
other high-performance modules for reading large data files or using the GPU to further accelerate performance
for an additional, modest charge. Most importantly, installation is extraordinarily easy on Windows, Linux, and
OS X. Anaconda is also simple to update to the latest version using

conda update conda


conda update anaconda

Windows

Installation on Windows requires downloading the installer and running. Anaconda comes in both Python
2.7 and 3.x flavors, and the latest Python 3.x is required. These instructions use ANACONDA to indicate
the Anaconda installation directory (e.g., the default is C:\Anaconda). Once the setup has completed, open a
PowerShell command prompt and run
cd ANACONDA\Scripts
conda init powershell
conda update conda
conda update anaconda
conda install html5lib seaborn jupyterlab

which will first ensure that Anaconda is up-to-date. conda install can be used later to install other packages
that may be of interest. Note that if Anaconda is installed into a directory other than the default, the full path
should not contain Unicode characters or spaces.

Notes

The recommended settings for installing Anaconda on Windows are:

• Install for all users, which requires admin privileges. If these are not available, then choose the “Just
for me” option, but be aware of installing on a path that contains non-ASCII characters which can cause
issues.
1.5 Using Python 5

• Run conda init powershell to ensure that Anaconda commands can be run from the PowerShell
prompt.

• Register Anaconda as the system Python unless you have a specific reason not to (unlikely).

Linux and OS X

Installation on Linux requires executing


bash Anaconda3-x.y.z-Linux-ISA.sh

where x.y.z will depend on the version being installed and ISA will be either x86 or more likely x86_64.
Anaconda comes in both Python 2.7 and 3.x flavors, and the latest Python 3.x is required. The OS X installer is
available either in a GUI installed (pkg format) or as a bash installer which is installed in an identical manner to
the Linux installation. It is strongly recommended that the anaconda/bin is prepended to the path. This can be
performed in a session-by-session basis by entering conda init bash and then restarting your terminal. Note
that other shells such as zsh are also supported, and can be initialized by replacing bash with the name of your
preferred shell.
After installation completes, execute
conda update conda
conda update anaconda
conda install html5lib seaborn jupyterlab

which will first ensure that Anaconda is up-to-date and then install some optional modules. conda install
can be used later to install other packages that may be of interest.

Notes

All instructions for OS X and Linux assume that conda init bash has been run. If this is not the case, it is
necessary to run

cd ANACONDA
cd bin

and then all commands must be prepended by a . as in

./conda update conda

1.5 Using Python


Python can be programmed using an interactive session using IPython or by directly executing Python scripts
– text files that end with the extension .py – using the Python interpreter.

1.5.1 Python and IPython


Most of this introduction focuses on interactive programming, which has some distinct advantages when learn-
ing a language. The standard Python interactive console is very basic and does not support useful features such
as tab completion. IPython, and especially the QtConsole version of IPython, transforms the console into a
highly productive environment which supports a number of useful features:
6 Introduction

• Tab completion - After entering 1 or more characters, pressing the tab button will bring up a list of
functions, packages, and variables which match the typed text. If the list of matches is large, pressing tab
again allows the arrow keys can be used to browse and select a completion.
• “Magic” function which make tasks such as navigating the local file system (using %cd ~/directory/
or just cd ~/directory/ assuming that %automagic is on) or running other Python programs (using
run program.py) simple. Entering %magic inside and IPython session will produce a detailed
description of the available functions. Alternatively, %lsmagic produces a succinct list of available
magic commands. The most useful magic functions are

– cd - change directory
– edit filename - launch an editor to edit filename
– ls or ls pattern - list the contents of a directory
– run filename - run the Python file filename
– timeit - time the execution of a piece of code or function
– history - view commands recently run. When used with the -l switch, the history of previous ses-
sions can be viewed (e.g., history -l 100 will show the most recent 100 commands irrespective
of whether they were entered in the current IPython session of a previous one).

• Integrated help - When using the QtConsole, calling a function provides a view of the top of the help
function. For example, entering mean( will produce a view of the top 20 lines of its help text.
• Inline figures - Both the QtConsole and the notebook can also display figure inline which produces a
tidy, self-contained environment. This can be enabled by entering %matplotlib inline in an IPython
session.
• The special variable _ contains the last result in the console, and so the most recent result can be saved
to a new variable using the syntax x = _.
• Support for profiles, which provide further customization of sessions.

1.5.2 Launching IPython


OS X and Linux

IPython can be started by running


ipython

in the terminal. IPython using the QtConsole can be started using


jupyter qtconsole

A single line launcher on OS X or Linux can be constructed using


bash -c "jupyter qtconsole"

This single line launcher can be saved as filename.command where filename is a meaningful name (e.g. IPython-
Terminal) to create a launcher on OS X by entering the command
chmod 755 /FULL/PATH/TO/filename.command

The same command can to create a Desktop launcher on Ubuntu by running


sudo apt-get install --no-install-recommends gnome-panel
gnome-desktop-item-edit ~/Desktop/ --create-new

and then using the command as the Command in the dialog that appears.
1.5 Using Python 7

Figure 1.1: IPython running in the Windows Terminal app.

Windows (Anaconda)

To run IPython open PowerShell and enter IPython in the start menu. Starting IPython using the QtConsole
is similar and is simply called QtConsole in the start menu. Launching IPython from the start menu should
create a window similar to that in figure 1.1.
Next, run

jupyter qtconsole --generate-config

in the terminal or command prompt to generate a file named jupyter_qtconsole_config.py. This file contains
settings that are useful for customizing the QtConsole window. A few recommended modifications are

c.ConsoleWidget.font_size = 12
c.ConsoleWidget.font_family = "Bitstream Vera Sans Mono"
c.JupyterWidget.syntax_style = "monokai"

These commands assume that the Bitstream Vera fonts have been locally installed, which are available from
http://ftp.gnome.org/pub/GNOME/sources/ttf-bitstream-vera/1.10/. Opening Qt-
Console should create a window similar to that in figure 1.2 (although the appearance might differ) if you
did not use the recommendation configuration.

1.5.3 Getting Help


Help is available in IPython sessions using help(function). Some functions (and modules) have very long help
files. When using IPython, these can be paged using the command ?function or function? so that the text can be
scrolled using page up and down and q to quit. ??function or function?? can be used to type the entire function
including both the docstring and the code.

1.5.4 Running Python programs


While interactive programming is useful for learning a language or quickly developing some simple code,
complex projects require the use of complete programs. Programs can be run either using the IPython magic
8 Introduction

Figure 1.2: IPython running in a QtConsole session.

work %run program.py or by directly launching the Python program using the standard interpreter using
python program.py. The advantage of using the IPython environment is that the variables used in the
program can be inspected after the program run has completed. Directly calling Python will run the program
and then terminate, and so it is necessary to output any important results to a file so that they can be viewed
later.3
To test that you can successfully execute a Python program, input the code in the block below into a text
file and save it as firstprogram.py.
# First Python program
import time

print("Welcome to your first Python program.")


input("Press enter to exit the program.")
print("Bye!")
time.sleep(2)

Once you have saved this file, open the console, navigate to the directory you saved the file and enter python
firstprogram.py. Finally, run the program in IPython by first launching IPython, and the using %cd to
change to the location of the program, and finally executing the program using %run firstprogram.py.

1.5.5 %pylab and %matplotlib


When writing Python code, only a small set of core functions and variable types are available in the interpreter.
The standard method to access additional variable types or functions is to use imports, which explicitly al-
low access to specific packages or functions. While it is best practice to only import required functions or
packages, there are many functions in multiple packages that are commonly encountered in these notes. Pylab
is a collection of common NumPy, SciPy and Matplotlib functions that can be easily imported using a single
command in an IPython session, %pylab. This is nearly equivalent to calling from pylab import ⁎, since it
also sets the backend that is used to draw plots. The backend can be manually set using %pylab backend where
3
Programs can also be run in the standard Python interpreter using the command:
exec(compile(open(’filename.py’).read(),’filename.py’,’exec’))
1.5 Using Python 9

Figure 1.3: A successful test that matplotlib, IPython, NumPy and SciPy were all correctly installed.

backend is one of the available backends (e.g., qt5 or inline). Similarly %matplotlib backend can be used to
set just the backend without importing all of the modules and functions come with %pylab .
Most chapters assume that %pylab has been called so that functions provided by NumPy can be called
without explicitly importing them.

1.5.6 Testing the Environment


To make sure that you have successfully installed the required components, run IPython using shortcut or by
running ipython or jupyter qtconsole run in a terminal window. Enter the following commands,
one at a time (the meaning of the commands will be covered later in these notes).
>>> %pylab qt5
>>> x = randn(100,100)
>>> y = mean(x,0)
>>> import seaborn
>>> plot(y)
>>> import scipy as sp

If everything was successfully installed, you should see something similar to figure 1.3.

1.5.7 jupyterlab notebooks


A jupyter notebook is a simple and useful method to share code with others. Notebooks allow for a fluid
synthesis of formatted text, typeset mathematics (using LATEX via MathJax) and Python. The primary method
for using notebooks is through a web interface, which allows creation, deletion, export and interactive editing
of notebooks.
10 Introduction

Figure 1.4: The default IPython Notebook screen showing two notebooks.

To launch the jupyterlab server, open a command prompt or terminal and enter

jupyter lab

This command will start the server and open the default browser which should be a modern version of Chrome
(preferable), Chromium, Firefox or Edge. If the default browser is Safari or Internet Explorer, the URL can
be copied and pasted into Chrome. The first screen that appears will look similar to figure 1.4, except that the
list of notebooks will be empty. Clicking on New Notebook will create a new notebook, which, after a bit of
typing, can be transformed to resemble figure 1.5. Notebooks can be imported by dragging and dropping and
exported from the menu inside a notebook.

1.5.8 Integrated Development Environments


As you progress in Python and begin writing more sophisticated programs, you will find that using an Integrated
Development Environment (IDE) will increase your productivity. Most contain productivity enhancements
such as built-in consoles, code completion (or IntelliSense, for completing function names) and integrated
debugging. Discussion of IDEs is beyond the scope of these notes, although Spyder is a reasonable choice
(free, cross-platform). Visual Studio Code is an excellent alternative. My preferred IDE is PyCharm, which has
a community edition that is free for use (the professional edition is low cost for academics).

spyder

spyder is an IDE specialized for use in scientific applications of Python rather than for general purpose applica-
tion development. This is both an advantage and a disadvantage when compared to a full featured IDE such as
PyCharm or VS Code. The main advantage is that many powerful but complex features are not integrated into
Spyder, and so the learning curve is much shallower. The disadvantage is similar - in more complex projects,
or if developing something that is not straight scientific Python, Spyder is less capable. However, netting these
1.6 Exercises 11

Figure 1.5: A jupyterlab notebook showing formatted markdown, LATEX math and cells containing code.

two, Spyder is almost certainly the IDE to use when starting Python, and it is always relatively simple to migrate
to a sophisticated IDE if needed.
Spyder is started by entering spyder in the terminal or command prompt. A window similar to that in
figure 1.6 should appear. The main components are the editor (1), the object inspector (2), which dynamically
will show help for functions that are used in the editor, and the console (3). By default, Spyder opens a standard
Python console, although it also supports using the more powerful IPython console. The object inspector
window, by default, is grouped with a variable explorer, which shows the variables that are in memory and the
file explorer, which can be used to navigate the file system. The console is grouped with an IPython console
window (needs to be activated first using the Interpreters menu along the top edge), and the history log which
contains a list of commands executed. The buttons along the top edge facilitate saving code, running code and
debugging.

1.6 Exercises
1. Install Python.
2. Test the installation using the code in section 1.5.6.
3. Customize IPython QtConsole using a font or color scheme. More customization options can be found
by running ipython -h.
4. Explore tab completion in IPython by entering a<TAB> to see the list of functions which start with a and
are loaded by pylab. Next try i<TAB>, which will produce a list longer than the screen – press ESC to
exit the pager.
5. Launch IPython Notebook and run code in the testing section.
6. Open Spyder and explore its features.
12 Introduction

Figure 1.6: The default Spyder IDE on Windows.

1.A Additional Installation Issues


1.A.1 Frequently Encountered Problems
All
Whitespace sensitivity

Python is whitespace sensitive and so indentation, either spaces or tabs, affects how Python interprets files. The
configuration files, e.g. ipython_config.py, are plain Python files and so are sensitive to whitespace. Introducing
white space before the start of a configuration option will produce an error, so ensure there is no whitespace
before active lines of a configuration.

Windows
Spaces in path

Python may work when directories have spaces.

Unicode in path

Python does not always work well when a path contains Unicode characters, which might occur in a user
name. While this isn’t an issue for installing Python or Anaconda, it is an issue for IPython which looks
in c:\user\username\.ipython for configuration files. The solution is to define the HOME variable before
launching IPython to a path that has only ASCII characters.

mkdir c:\anaconda\ipython_config
set HOME=c:\anaconda\ipython_config
1.A Additional Installation Issues 13

c:\Anaconda\Scripts\activate econometrics
ipython profile create econometrics
ipython --profile=econometrics

The set HOME=c:\anaconda\ipython_config can point to any path with directories containing only ASCII
characters, and can also be added to any batch file to achieve the same effect.

OS X
Installing Anaconda to the root of the partition

If the user account used is running as root, then Anaconda may install to /anaconda and not ~/anaconda by
default. Best practice is not to run as root, although in principle this is not a problem, and /anaconda can be
used in place of ~/anaconda in any of the instructions.

1.A.2 Setup using Virtual Environments


The simplest method to install the Python scientific stack is to use directly Continuum Analytics’ Anaconda.
These instructions describe alternative installation options using virtual environments, which allow alternative
configurations to simultaneously co-exist on a single system. The primary advantage of a virtual environment
is that it allows package versions to be frozen so that code that upgrading a module or all of Anaconda does not
upgrade the packages in a particular virtual environment.

Windows

Installation on Windows requires downloading the installer and running. These instructions use ANACONDA
to indicate the Anaconda installation directory (e.g. the default is C:\Anaconda). Once the setup has completed,
open a PowerShell prompt and run
cd ANACONDA\Scripts
conda init powershell
conda update conda
conda update anaconda
conda create -n econometrics qtconsole notebook matplotlib numpy pandas scipy spyder
statsmodels
conda install -n econometrics cython lxml nose numba numexpr pytables sphinx xlrd xlwt
html5lib seaborn

which will first ensure that Anaconda is up-to-date and then create a virtual environment named economet-
rics. Using a virtual environment is a best practice and is important since component updates can lead to
errors in otherwise working programs due to backward incompatible changes in a module. The long list of
modules in the conda create command includes the core modules. conda install contains the remain-
ing packages and is shown as an example of how to add packages to an existing virtual environment af-
ter it has been created. It is also possible to install all available Anaconda packages using the command
conda create -n econometrics anaconda.
The econometrics environment must be activated before use. This is accomplished by running
conda activate econometrics

from the command prompt, which prepends [econometrics] to the prompt as an indication that virtual environ-
ment is active. Activate the econometrics environment and then run
cd c:\
ipython
14 Introduction

which will open an IPython session using the newly created virtual environment.
Virtual environments can also be created using specific versions of packages using pinning. For example,
to create a virtual environment names old using Python 3.6 and NumPy 1.16,

conda create -n old python=3.6 numpy=1.16 scipy pandas

which will install the requested versions of Python and NumPy as well as the latest version of SciPy and pandas
that are compatible with the pinned versions.

Linux and OS X

Installation on Linux requires executing


bash Anaconda3-x.y.z-Linux-ISA.sh

where x.y.z will depend on the version being installed and ISA will be either x86 or more likely x86_64. The
OS X installer is available either in a GUI installed (pkg format) or as a bash installer which is installed in an
identical manner to the Linux installation. After installation completes, change to the folder where Anaconda
installed (written here as ANACONDA, default ~/anaconda) and execute
cd ANACONDA
cd bin
./conda init bash
./conda update conda
./conda update anaconda
./conda create -n econometrics qtconsole notebook matplotlib numpy pandas scipy spyder
statsmodels
./conda install -n econometrics cython lxml nose numba numexpr pytables sphinx xlrd xlwt
html5lib seaborn

which will first ensure that Anaconda is up-to-date and then create a virtual environment named econometrics
with the required packages. conda create creates the environment and conda install installs additional
packages to the existing environment. conda install can be used later to install other packages that may be
of interest. To activate the newly created environment, run
conda activate econometrics

and then run the command


ipython

to launch IPython using the newly created virtual environment.


Chapter 2

Built-in Data Types

Before diving into Python for analyzing data or running Monte Carlos, it is necessary to understand some basic
concepts about the core Python data types. Unlike domain-specific languages such as MATLAB or R, where
the default data type has been chosen for numerical work, Python is a general purpose programming language
which is also well suited to data analysis, econometrics, and statistics. For example, the basic numeric type in
MATLAB is an array (using double precision, which is useful for floating point mathematics), while the basic
numeric data type in Python is a 1-dimensional scalar which may be either an integer or a double-precision
floating point, depending on the formatting of the number when input.

2.1 Variable Names


Variable names can take many forms, although they can only contain numbers, letters (both upper and lower),
and underscores (_). They must begin with a letter or an underscore and are CaSe SeNsItIve. Additionally,
some words are reserved in Python and so cannot be used for variable names (e.g. import or for). For example,
x = 1.0
X = 1.0
X1 = 1.0
X1 = 1.0
x1 = 1.0
dell = 1.0
dellreturns = 1.0
dellReturns = 1.0
_x = 1.0
x_ = 1.0

are all legal and distinct variable names. Note that names which begin or end with an underscore, while legal,
are not normally used since by convention these convey special meaning.1 Illegal names do not follow these
rules.
# Not allowed
x: = 1.0
1X = 1
X-1 = 1
for = 1
1
Variable names with a single leading underscore, for example _some_internal_value, indicate that the variable is for internal
use by a module or class. While indicated to be private, this variable will generally be accessible by calling code. Double leading
underscores, for example __some_private_value, indicate that a value is actually private and is not accessible. Variable names
with trailing underscores are used to avoid conflicts with reserved Python words such as class_ or lambda_. Double leading and
trailing underscores are reserved for “magic” variable (e.g. __init__) , and so should be avoided except when specifically accessing
a feature.
16 Built-in Data Types

Multiple variables can be assigned on the same line using commas,


x, y, z = 1, 3.1415, 'a'

2.2 Core Native Data Types


2.2.1 Numeric
Simple numbers in Python can be either integers, floats or complex. This chapter does not cover all Python data
types and instead focuses on those which are most relevant for numerical analysis, econometrics, and statistics.
The byte, bytearray and memoryview data types are not described.

2.2.1.1 Floating Point (float)

The most important (scalar) data type for numerical analysis is the float. Unfortunately, not all non-complex
numeric data types are floats. To input a floating data type, it is necessary to include a . (period, dot) in the
expression. This example uses the function type() to determine the data type of a variable.
>>> x = 1
>>> type(x)
int

>>> x = 1.0
>>> type(x)
float

>>> x = float(1)
>>> type(x)
float

This example shows that using the expression that x = 1 produces an integer-valued variable while x = 1.0
produces a float-valued variable. Using integers can produce unexpected results and so it is important to include
“.0” when expecting a float.

2.2.1.2 Complex (complex)

Complex numbers are also important for numerical analysis. Complex numbers are created in Python using j
or the function complex().
>>> x = 1.0
>>> type(x)
float

>>> x = 1j
>>> type(x)
complex

>>> x = 2 + 3j
>>> x
(2+3j)

>>> x = complex(1)
>>> x
(1+0j)

Note that a+bj is the same as complex(a,b), while complex(a) is the same as a+0j.
2.2 Core Native Data Types 17

2.2.1.3 Integers (int)

Floats use an approximation to represent numbers which may contain a decimal portion. The integer data
type stores numbers using an exact representation, so that no approximation is needed. The cost of the exact
representation is that the integer data type cannot express anything that isn’t an integer, rendering integers of
limited use in most numerical work.
Basic integers can be entered either by excluding the decimal (see float), or explicitly using the int()
function. The int() function can also be used to convert a float to an integer by round towards 0.
>>> x = 1
>>> type(x)
int

>>> x = 1.0
>>> type(x)
float

>>> x = int(x)
>>> type(x)
int

Python integers support have unlimited range since the amount of bits used to store an integer is dynamic.
>>> x = 1
>>> x
1

>>> type(x)
int

>>> x = 2 ⁎⁎ 127 + 2 ⁎⁎ 65 # ⁎⁎ is denotes exponentiation, y^64 in TeX


>>> x
170141183460469231768580791863303208960

2.2.2 Boolean (bool)

The Boolean data type is used to represent true and false, using the reserved keywords True and False. Boolean
variables are important for program flow control (see Chapter 12) and are typically created as a result of logical
operations (see Chapter 10), although they can be entered directly.
>>> x = True
>>> type(x)
bool

>>> x = bool(1)
>>> x
True

>>> x = bool(0)
>>> x
False

Non-zero, non-empty values generally evaluate to true when evaluated by bool(). Zero or empty values such
as bool(0), bool(0.0), bool(0.0j), bool(None), bool('') and bool([]) are all false.
18 Built-in Data Types

2.2.3 Strings (str)


Strings are not usually important for numerical analysis, although they are frequently encountered when dealing
with data files, especially when importing or when formatting output for human consumption. Strings are
delimited using single quotes ('') or double quotes ("") but not using combination of the two delimiters (i.e.,
do not use '") in a single string, except when used to express a quotation.
>>> x = 'abc'
>>> type(x)
str

>>> y = '"A quotation!"'


>>> print(y)
"A quotation!"

String manipulation is further discussed in Chapter 23.

2.2.3.1 Slicing Strings

Substrings within a string can be accessed using slicing. Slicing uses [] to contain the indices of the characters
in a string, where the first index is 0, and the last is n − 1 (assuming the string has n letters). The following
table describes the types of slices which are available. The most useful are s[i], which will return the character
in position i, s[:i], which return the leading characters from positions 0 to i − 1, and s[i:] which returns the
trailing characters from positions i to n − 1. The table below provides a list of the types of slices which can
be used. The second column shows that slicing can use negative indices which essentially index the string
backward.

Slice Behavior
s[:] Entire string
s[i] Charactersi
s[i:] Charactersi, . . . , n − 1
s[:i] Characters0, . . . , i − 1
s[i: j ] Charactersi, . . . , j − 1
s[i: j :m] Charactersi,i + m,. . .i + m⌊ j−i−1
m ⌋
s[−i] Characters n − i
s[−i:] Charactersn − i, . . . , n − 1
s[:−i] Characters0, . . . , n − i − 1
s[− j :−i] Characters n − j, . . . , n − i − 1, − j < −i
s[− j :−i:m] Characters n − j,n − j + m,. . .,n − j + m⌊ j−i−1
m ⌋

>>> text = 'Python strings are sliceable.'


>>> text[0]
'P'

>>> text[10]
'i'

>>> L = len(text)
>>> text[L] # Error
IndexError: string index out of range

>>> text[L-1]
2.2 Core Native Data Types 19

'.'

>>> text[:10]
'Python str'

>>> text[10:]
'ings are sliceable.'

2.2.4 Lists (list)

Lists are a built-in container data type which hold other data. A list is a collection of other objects – floats,
integers, complex numbers, strings or even other lists. Lists are essential to Python programming and are used
to store collections of other values. For example, a list of floats can be used to express a vector (although the
NumPy data type array is better suited to working with collections of numeric values). Lists also support
slicing to retrieve one or more elements. Basic lists are constructed using square braces, [], and values are
separated using commas.

>>> x = []
>>> type(x)
builtins.list

>>> x=[1,2,3,4]
>>> x
[1,2,3,4]

# 2-dimensional list (list of lists)


>>> x = [[1,2,3,4], [5,6,7,8]]
>>> x
[[1, 2, 3, 4], [5, 6, 7, 8]]

# Jagged list, not rectangular


>>> x = [[1,2,3,4] , [5,6,7]]
>>> x
[[1, 2, 3, 4], [5, 6, 7]]

# Mixed data types


>>> x = [1,1.0,1+0j,'one',None,True]
>>> x
[1, 1.0, (1+0j), 'one', None, True]

These examples show that lists can be regular, nested and can contain any mix of data types including other
lists.

2.2.4.1 Slicing Lists

Lists, like strings, can be sliced. Slicing is similar, although lists can be sliced in more ways than strings. The
difference arises since lists can be multi-dimensional while strings are always 1×n. Basic list slicing is identical
to slicing strings, and operations such as x[:], x[1:], x[:1] and x[-3:] can all be used. To understand slicing,
assume x is a 1-dimensional list with n elements and i ≥ 0, j > 0, i < j,m ≥ 1. Python uses 0-based indices, and
so the n elements of x can be thought of as x0 , x1 , . . . , xn−1 .
20 Built-in Data Types

Slice Behavior, Slice Behavior


x[:] Return all x x[−i] Returns xn−i except when i = −0
x[i] Return xi x[−i:] Return xn−i , . . . , xn−1
x[i:] Return xi , . . . xn−1 x[:−i] Return x0 , . . . , xn−i−1
x[:i] Return x0 , . . . , xi−1 x[− j:−i] Return xn− j , . . . , xn−i−1
x[i: j] Return xi , xi+1 , . . . x j−1 x[− j:−i:m] Returns xn− j ,xn− j+m ,. . .,xn− j+m⌊ j−i−1 ⌋
m
x[i: j:m] Returns xi ,xi+m ,. . .xi+m⌊ j−i−1 ⌋
m

The default list slice uses a unit stride (step size of one) . It is possible to use other strides using a third
input in the slice so that the slice takes the form x[i:j:m] where i is the index to start, j is the index to end
(exclusive) and m is the stride length. For example x[::2] will select every second element of a list and is
equivalent to x[0:n:2] where n = len(x). The stride can also be negative which can be used to select the
elements of a list in reverse order. For example, x[::-1] will reverse a list and is equivalent to x[0:n:-1] .
Examples of accessing elements of 1-dimensional lists are presented below.
>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> x[0]
0
>>> x[5]
5
>>> x[10] # Error
IndexError: list index out of range
>>> x[4:]
[4, 5, 6, 7, 8, 9]
>>> x[:4]
[0, 1, 2, 3]
>>> x[1:4]
[1, 2, 3]
>>> x[-0]
0
>>> x[-1]
9
>>> x[-10:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]

List can be multidimensional, and slicing can be done directly in higher dimensions. For simplicity, consider
slicing a 2-dimensional list x = [[1,2,3,4], [5,6,7,8]]. If single indexing is used, x[0] will return the
first (inner) list, and x[1] will return the second (inner) list. Since the list returned by x[0] is sliceable, the
inner list can be directly sliced using x[0][0] or x[0][1:4].
>>> x = [[1,2,3,4], [5,6,7,8]]
>>> x[0]
[1, 2, 3, 4]
>>> x[1]
[5, 6, 7, 8]
>>> x[0][0]
1
>>> x[0][1:4]
[2, 3, 4]
>>> x[1][-4:-1]
[5, 6, 7]

2.2.4.2 List Functions

A number of functions are available for manipulating lists. The most useful are
2.2 Core Native Data Types 21

Function Method Description


list.append(x,value) x.append(value) Appends value to the end of the list.
len(x) – Returns the number of elements in the list.
list.extend(x,list) x.extend(list) Appends the values in list to the existing list.2
list.pop(x,index) x.pop(index) Removes the value in position index and returns the value.
list.remove(x,value) x.remove(value) Removes the first occurrence of value from the list.
list.count(x,value) x.count(value) Counts the number of occurrences of value in the list.
del x[slice] Deletes the elements in slice.

>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> x.append(0)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

>>> len(x)
11

>>> x.extend([11,12,13])
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13]

>>> x.pop(1)
1

>>> x
[0, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13]

>>> x.remove(0)
>>> x
[2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13]

Elements can also be deleted from lists using the keyword del in combination with a slice.
>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> del x[0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> x[:3]
[1, 2, 3]

>>> del x[:3]


>>> x
[4, 5, 6, 7, 8, 9]

>>> del x[1:3]


>>> x
[4, 7, 8, 9]

>>> del x[:]


>>> x
[]

2.2.5 Tuples (tuple)


A tuple is virtually identical to a list with one important difference – tuples are immutable. Immutability means
that a tuple cannot be changed once created. It is not possible to add, remove, or replace elements in a tuple.
22 Built-in Data Types

However, if a tuple contains a mutable data type, for example a tuple that contains a list, the contents mutable
data type can be altered.
Tuples are constructed using parentheses (()) in place of the square brackets ([]) used to create lists. Tuples
can be sliced in an identical manner as lists. A list can be converted into a tuple using tuple() (Similarly, a
tuple can be converted to list using list()).
>>> x =(0,1,2,3,4,5,6,7,8,9)
>>> type(x)
tuple

>>> x[0]
0

>>> x[-10:-5]
(0, 1, 2, 3, 4)

>>> x = list(x)
>>> type(x)
list

>>> x = tuple(x)
>>> type(x)
tuple

>>> x= ([1,2],[3,4])
>>> x[0][1] = -10
>>> x # Contents can change, elements cannot
([1, -10], [3, 4])

Note that tuples containing a single element must contain a comma when created, so that x = (2,) is assign
a tuple to x, while x=(2) will assign 2 to x. The latter interprets the parentheses as if they are part of a
mathematical formula rather than being used to construct a tuple. x = tuple([2]) can also be used to create a
single element tuple. Lists do not have this issue since square brackets do not have this ambiguity.
>>> x =(2)
>>> type(x)
int

>>> x = (2,)
>>> type(x)
tuple

>>> x = tuple([2])
>>> type(x)
tuple

2.2.5.1 Tuple Functions

Tuples are immutable, and so only have the methods index and count, which behave in an identical manner to
their list counterparts.

2.2.6 Dictionary (dict)


Dictionaries are encountered far less frequently than then any of the previously described data types in numer-
ical Python. They are, however, commonly used to pass options into other functions such as optimizers, and
so familiarity with dictionaries is important. Dictionaries in Python are composed of keys (words) and values
2.2 Core Native Data Types 23

(definitions). Dictionaries keys must be unique immutable data types (e.g. strings, the most common key, in-
tegers, or tuples containing immutable types), and values can contain any valid Python data type.3 Values are
accessed using keys.
>>> data = {'age': 34, 'children' : [1,2], 1: 'apple'}
>>> type(data)
dict

>>> data['age']
34

Values associated with an existing key can be updated by making an assignment to the key in the dictionary.
>>> data['age'] = 'xyz'
>>> data['age']
'xyz'

New key-value pairs can be added by defining a new key and assigning a value to it.
>>> data['name'] = 'abc'
>>> data
{1: 'apple', 'age': 'xyz', 'children': [1, 2], 'name': 'abc'}

Key-value pairs can be deleted using the reserved keyword del.


>>> del data['age']
>>> data
{1: 'apple', 'children': [1, 2], 'name': 'abc'}

2.2.7 Sets (set, frozenset)


Sets are collections which contain all unique elements of a collection. set and frozenset only differ in that the
latter is immutable (and so has higher performance), and so set is similar to a unique list while frozenset
is similar to a unique tuple . While sets are generally not important in numerical analysis, they can be very
useful when working with messy data – for example, finding the set of unique tickers in a long list of tickers.

2.2.7.1 Set Functions

A number of methods are available for manipulating sets. The most useful are
Function Method Description
set.add(x,element) x.add(element) Appends element to a set.
len(x) – Returns the number of elements in the set.
set.difference(x,set) x.difference(set) Returns the elements in x which are not in set.
set.intersection(x,set) x.intersection(set) Returns the elements of x which are also in set.
set.remove(x,element) x.remove(element) Removes element from the set.
set.union(x,set) x.union(set) Returns the set containing all elements of x and set.

The code below demonstrates the use of set. Note that 'MSFT' is repeated in the list used to initialize the
set, but only appears once in the set since all elements must be unique.
>>> x = set(['MSFT','GOOG','AAPL','HPQ','MSFT'])
>>> x
{'AAPL', 'GOOG', 'HPQ', 'MSFT'}

3
Formally dictionary keys must support the __hash__ function, equality comparison and it must be the case that different keys
have different hashes.
24 Built-in Data Types

>>> x.add('CSCO')
>>> x
{'AAPL', 'CSCO', 'GOOG', 'HPQ', 'MSFT'}

>>> y = set(['XOM', 'GOOG'])


>>> x.intersection(y)
{'GOOG'}

>>> x = x.union(y)
>>> x
{'AAPL', 'CSCO', 'GOOG', 'HPQ', 'MSFT', 'XOM'}

>>> x.remove('XOM')
{'AAPL', 'CSCO', 'GOOG', 'HPQ', 'MSFT'}

A frozenset supports the same methods except add and remove.

2.2.8 range
A range is most commonly encountered in a for loop. range(a,b,i) creates the sequences that follows
the pattern a, a + i, a + 2i, . . . , a + (m − 1)i where m = ⌈ b−a
i ⌉. In other words, it find all integers x starting with
a such a ≤ x < b and where two consecutive values are separated by i. range can be called with 1 or two
parameters – range(a,b) is the same as range(a,b,1) and range(b) is the same as range(0,b,1).
>>> x = range(10)
>>> type(x)
range

>>> print(x)
range(0, 10)

>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> x = range(3,10)
>>> list(x)
[3, 4, 5, 6, 7, 8, 9]

>>> x = range(3,10,3)
>>> list(x)
[3, 6, 9]

range is not technically a list, which is why the statement print(x) returns range(0,10). Explicitly
converting with list produces a list which allows the values to be printed. range is technically an iterator
which does not actually require the storage space of a list.

2.3 Additional Container Data Types in the Standard Library


Python includes an extensive standard library that provides many features that extend the core Python language.
Data types in the standard library are always installed alongside the Python interpreter. However, they are not
“built-in” since using one requires an explicit import statement to make a particular data type available. The
standard library is vast and some examples of the included functionality are support for working with dates
(provided by the datetime module, see Chapter 14), functional programming tools (itertools , functools
and operator), tools for accessing the file system (os.path and glob inter alia., see Chapter 24), and support
for interacting with resources on the the internet (urllib and ftplib inter alia.). One of the more useful
modules included in the standard library is the collections module. This module provides a set of specialized
2.3 Additional Container Data Types in the Standard Library 25

container data types that extend the built-in data container data types. Two are particularly useful when working
with data: OrderedDict and defaultdict. Both of these extend the built-in dictionary dict with useful
features.

2.3.1 OrderedDict
When using a standard Python dict, items order is not guaranteed. OrderedDict addresses this frequent short-
coming by retaining a list of the keys inserted into the dictionary in the order in which they have been inserted.
The order is also preserved when deleting keys from an OrderedDict.
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od['key1'] = 1
>>> od['key2'] = 'a'
>>> od['key3'] = 'alpha'
>>> plain = dict(od)
>>> print(list(od.keys()))
['key1', 'key2', 'key3']

>>> print(list(plain.keys()))
['key2', 'key1', 'key3']

>>> del od['key1']


>>> print(list(od.keys()))
['key2', 'key3']

>>> od['key1'] = 'some other value'


print(list(od.keys()))
['key2', 'key3', 'key1']

This functionality is particularly useful when iterating over the keys in a dictionary since it guarantees a pre-
dictable order when accessing the keys (see Chapter 12). Recent versions of pandas also respect the order in an
OrderedDict when adding columns to a DataFrame (see Chapter 16).

2.3.2 defaultdict
By default attempting to access a key in a dictionary that does not exist will produce an error. There are
circumstances where this is undesirable, and when a key is encountered that doesn’t exist, a default value
should be added to the dictionary and returns. One particularly useful example of this behavior is when making
keyed lists – that is, grouping like elements according to a key in a list. If the key exists, the elements should
be appended to the existing list. If the key doesn’t exist, the key should be added and a new list containing the
new element should be inserted into the disctionary. defaultdict enables this exact scenario by accepting a
callable function as an argument. When a key is found, it behaved just like a standard dictionary. When a key
isn’t found, the output of the callable function is assigned to the key. This example uses list to add a new list
whenever a key is not found.
>>> d = {}
>>> d['one'].append('an item') # Error
KeyError: 'one'

>>> from collections import defaultdict


>>> dd = defaultdict(list)
>>> dd['one'].append('first')
>>> dd['one'].append('second')
>>> dd['two'].append('third')
>>> print(dd)
26 Built-in Data Types

defaultdict(<class 'list'>, {'one': ['first', 'second'], 'two': ['third']})

The callable argument provided to defaultdict can be anything that is useful including other containers,
objects that will be initialized the first time called, or an anonymous function (i.e. a function defined using
lambda, see Section 18.4).

2.4 Python and Memory Management


Python uses a highly optimized memory allocation system which attempts to avoid allocating unnecessary
memory. As a result, when one variable is assigned to another (e.g. to y = x), these will actually point to the
same data in the computer’s memory. To verify this, id() can be used to determine the unique identification
number of a piece of data.4
>>> x = 1
>>> y = x
>>> id(x)
82970264

>>> id(y)
82970264

>>> x = 2.0
>>> id(x)
93850568

>>> id(y)
82970264

In the above example, the initial assignment of y = x produced two variables with the same ID. However, once
x was changed, its ID changed while the ID of y did not, indicating that the data in each variable was stored
in different locations. This behavior is both safe and efficient and is common to the basic Python immutable
types: int, float, complex, string, tuple, frozenset and range.

2.4.1 Example: Lists


Lists are mutable and so assignment does not create a copy , and so changes to either variable affect both.
>>> x = [1, 2, 3]
>>> y = x
>>> y[0] = -10
>>> y
[-10, 2, 3]

>>> x
[-10, 2, 3]

Slicing a list creates a copy of the list and any immutable types in the list – but not mutable elements in the list.
>>> x = [1, 2, 3]
>>> y = x[:]
>>> id(x)
86245960

>>> id(y)
86240776

4
The ID numbers on your system will likely differ from those in the code listing.
2.5 Exercises 27

To see that the inner lists are not copied, consider the behavior of changing one element in a nested list.
>>> x=[[0,1],[2,3]]
>>> y = x[:]
>>> y
[[0, 1], [2, 3]]

>>> id(x[0])
117011656

>>> id(y[0])
117011656

>>> x[0][0]
0.0

>>> id(x[0][0])
30390080

>>> id(y[0][0])
30390080

>>> y[0][0] = -10.0


>>> y
[[-10.0, 1], [2, 3]]

>>> x
[[-10.0, 1], [2, 3]]

When lists are nested or contain other mutable objects (which do not copy), slicing copies the outermost list to
a new ID, but the inner lists (or other objects) are still linked. In order to copy nested lists, it is necessary to
explicitly call deepcopy(), which is in the module copy.
>>> import copy as cp
>>> x=[[0,1],[2,3]]
>>> y = cp.deepcopy(x)
>>> y[0][0] = -10.0
>>> y
[[-10.0, 1], [2, 3]]

>>> x
[[0, 1], [2, 3]]

2.5 Exercises
1. Enter the following into Python, assigning each to a unique variable name:

(a) 4
(b) 3.1415
(c) 1.0
(d) 2+4j
(e) 'Hello'
(f) 'World'

2. What is the type of each variable? Use type if you aren’t sure.
Random documents with unrelated
content Scribd suggests to you:
lungamente resistere a quell'impeto, e cercarono scampo fuggendo
per le finestre.
Avendo i Francesi piantato delle batterie, i di cui fuochi riescivano
oltremodo funesti ai Romani, Garibaldi mise mano a una via
sotterranea, che li conducesse a quella volta con animo di farle colle
mine saltare in aria, lo che impedivagli il nemico di mandare ad
effetto, col rivolgere le acque dentro i lavori già avanzati, e de' quali
egli s'era avveduto.
La sera del 10 meditando un audacissimo colpo, Garibaldi riuniva
buon nerbo di truppe nella piazza di s. Pietro, e fattele disporre per
una incamiciata, le conduceva fuori dei muri con ordine di avanzarsi
in silenzio e di scagliarsi al convenuto segnale sull'accampamento
nemico, colla baionetta alla mano. Un inaspettato contrattempo
faceva sì che l'avanguardia sparato qualche tiro prima di giungere al
luogo, rendesse avvertiti i Francesi dell'imminente pericolo e non più
eseguibile il preparato assalto.
Tale stizza i Francesi aveano concepito contro Garibaldi, che
allorquando appresero com'egli soleva dall'alto del palazzo nella villa
Corsini osservar le loro operazioni e dirigere i movimenti delle truppe
romane, cominciarono a far piovere sulla malaugurata casa e
cannonate e bombe in tal copia, che non molto dopo dovette
Garibaldi abbandonarla perchè interamente guasta e prossima a
crollare. Di là egli trasportò il suo quartiere nella villa Spada,
egualmente esposta ai tiri del nemico.
Spuntava frattanto il giorno 12, in cui il generale Oudinot, terminati i
lavori d'approccio, trovavasi in posizione di poter bombardare Roma;
per cui rivolgendosi alle autorità scriveva: che ove dopo 12 ore
dall'intimazione la città non si fosse arresa, avrebbela attaccata di
viva forza: al che il Triumvirato fermo nell'onorevole proposito: «Non
tradiamo mai le nostre promesse, rispondeva: abbiamo promesso
difendere l'onore del paese e la bandiera della Repubblica:
manterremo la nostra promessa.» E dodici ore dopo ricominciava più
che mai furiosa la pugna. Videro in quel giorno i Francesi tali prove
di audacia, di valore e di militare scienza, che ne maravigliarono
spaventati. Garibaldi dà di quella tremenda giornata, ch'egli dirigeva
in persona, un saggio nella relazione che trasmise al governo; ivi è
detto: «Il furore de' nostri era al colmo, poichè mancando di
munizioni, questi prodi colsero le pietre, e con esse sconfissero il
nemico, gli tolsero le baionette dai fucili, e se ne servirono come
d'un arma terribile.»
In tutti quei giorni di lotta che seguirono dal 13 al 22, Garibaldi fu
visto dì e notte continuamente nei luoghi ove più ferveva la
battaglia, ed era più evidente il pericolo: la gente non sapeva
com'egli potesse tanto assiduamente mostrarsi dovunque le
emergenze di que' fortunosi momenti richiedessero la presenza d'un
uomo che valesse col consiglio e l'audacia a debitamente
provvedervi. Egli pareva non sentir mai il bisogno del riposo o quello
del cibo: sarebbesi detto che nel fuoco e nelle aspre fatiche della
guerra prendessero le di lui membra ristoro e forze novelle.
Occasione di nuovi ingenti sforzi e di valore disperato diede a
Garibaldi la notte in cui i nemici per la lenta ma sicura via delle opere
d'assedio, apparvero dentro i muri della città. Trovavasi egli in quel
momento in un posto di riserva e non appena giungevagli l'infausta
notizia, che in un colle truppe accorreva ad assalire colla baionetta
calata il nemico, che in fortissimo numero già s'era trincerato nelle
prese posizioni. Tornata vana tanta virtù, egli non si perdeva d'animo
per questo; chè all'alba con nuovo furore avventavasi risolutamente
un'altra volta all'ardimentoso cimento. Spinse i soldati a metter piede
perfin sui lavori del nemico, e con tal impeto e dispregio del pericolo
il fece, che erasi condotto tanto innanzi, che i nostri toccavano le
punte delle carabine ai soldati nemici, le quali sopravanzavano dalle
paralelle. Pure anco questo secondo tentativo rimaneva pur troppo
senza frutto dinanzi all'ostacolo dei trinceramenti, senza di cui il
nemico avrebbe dovuto come già altre volte ritirarsi sanguinoso e
disfatto. Erano quelli momenti supremi, e la posizione tristissima; e
nonostante il coraggio e il desiderio di nuovi paragoni col nemico in
tutti raddoppiavansi allo spettacolo sublime di Garibaldi e de' suoi. —
Roma riviveva ai tempi antichi.
Dalla nuova posizione in cui s'erano fortificati, i Francesi
bombardarono senza posa per molti giorni la città, e gravissimi danni
arrecarono agli antichi monumenti, che altri barbari e in più barbari
tempi avevano rispettato. E la ferocia di codesti stranieri che non
offesi, nè provocati eran calati in Italia senz'altra ragione che il
numero [12], senz'altro diritto che il sangue, veniva spinta a tal grado,
che i consoli delle estere nazioni, indignati a tanto strazio diressero
al generale francese una nota nella quale protestando contro «quel
modo d'attaccare che non solo minacciava le proprietà e le vite dei
neutri abitanti, ma anche quelle delle donne e dei fanciulli,
chiedevano in nome dell'umanità e delle nazioni civili che desistesse
dal bombardare più oltre, per salvare dalla distruzione la città
monumentale che è considerata come sotto la protezione morale di
tutti i paesi inciviliti del mondo.»
In onta alla voce che il mondo cristiano sollevava per bocca de' suoi
rappresentanti in Roma contro il vandalismo de' soldati di Francia, le
bombe continuarono senza ristarsi un momento a cadere sull'eroica
capitale d'Italia, e quanto più codesti pretesi liberatori dei popoli
vedevansi da un piccol numero d'uomini, nuovi quasi tutti alle armi e
privi dei potenti mezzi di guerra, di cui essi potevano disporre,
contrastato il trionfo e sovente ancora battuti, tanto maggiormente
s'imbestialivano, e il concetto furore con atti crudelissimi
disfogavano. Poco pareva a costoro il fulminare notte e giorno la
città coi mortai e co' cannoni, che anche spingevano all'assalto i
soverchianti battaglioni; ma a traverso le tenebre, colla mira
d'introdursi non visti e per sorpresa, dacchè l'approssimarsi di giorno
e venire a far prova faccia a faccia del proprio valore coi nostri
avevano vedute tornar loro sempre a danno e a vergogna. E tale
esito ebbe il colpo tentato la notte del 25, in cui da tutti i punti
assaliti vennero coraggiosamente respinti. Ripeterono l'assalto la
notte del 27 giovandosi d'una fitta nebbia e attaccando colla
baionetta; ma non valse loro nè la sorpresa nè la risolutezza
dell'assalto, chè un muro insuperabile di petti cittadini s'oppose a
contrastarli il passo. Ivi s'accese una mischia talmente accanita da
ambe le parti, che durante tutta la notte si continuò a combattere, il
micidiale incontro protraendosi fino a tardi nel giorno seguente.
Garibaldi sempre in mezzo al fuoco aizzava i compagni in quel furore
e gli esortava a non cedere, a tener fermo per l'onore italiano, e
accorrendo dovunque accresceva l'animo e la rabbia nei combattenti.
«Voi pugnate per la libertà e per l'onore d'Italia!» era il suo grido
prediletto di guerra, e a quel grido raddoppiavansi come per incanto
i colpi, sotto i quali cadevano i Francesi a mordere quel mal tocco
terreno. L'orribile pioggia di bombe e di granate accompagnava
incessantemente quegli attacchi alle fortificazioni, protetti pur anco
dalle artiglierie che avevano già grandemente dilatato la breccia.
Sulla quale avendo finalmente i nemici lanciato il dì 30 un numero
sterminato d'uomini, poterono collocare una batteria che rendeva
quasi del tutto vana ogni ulteriore resistenza. Nonostante male
sapendo Garibaldi comportare quel trionfo del nemico, che oramai
non era più in poter d'uomo contrastare lungamente, egli volle far
prova di scacciarlo dalle occupate posizioni, e riuscivagli il colpo;
senonchè rivennero poco dopo i Francesi alla pugna, e dovè
Garibaldi ritirarsi non senza però ritentare la fortuna che sorridevagli
per l'ultima volta, poichè avendo nuovamente respinto il nemico,
quando tutto già pareva perduto, questi rinforzatosi con nuove
truppe, rese impossibile ad umana forza ogni altro tentativo.
Questi rovesci ben lungi dal far desistere Garibaldi da ogni idea
d'ulteriore resistenza avevanlo sempre più confermato nel pensiero
di continuarsi ad opporre al Francese nella terza cinta protetta dalle
barricate al di qua del Tevere, e dopo aver fatto rovinare il ponte di
S. Angelo e quello di Sisto. Se il magnanimo proposito non fu
mandato ad effetto, debbesi attribuire a cause che da lui non
dipesero, e le quali la storia, fedele custode delle umane azioni, farà
note più tardi.
Non patendo a Garibaldi l'animo di cedere le gloriose armi allo
straniero invasore, risolveva uscire da Roma, ed avventurarsi a nuovi
pericoli; e fatto appello ai compagni con queste parole che
riportiamo fedelmente:
Soldati,
Ciò che io offro a quanti vogliono seguitarmi, eccolo: fame, freddo,
sole. Non paga, non caserme, non munizioni, ma avvisaglie
continue, marce forzate e fazioni alla baionetta. — Chi ama la patria
e la gloria mi seguiti.
Garibaldi.
radunò circa 3,000 uomini coi quali s'avviò alla volta di Tivoli, non
lontano forse dal credere che mantenendosi per qualche tempo nella
campagna, avrebbe potuto riunire a sè maggiori e considerevoli
elementi onde organizzare una lunga resistenza contro gli stranieri,
che da due parti diverse aveano invaso l'Italia, e i quali ad un tempo
s'affaccendavano ad inseguirlo, ben mostrando come degli Austriaci
chiamati barbari non fossero punto dissimili codesti altri calati di
Francia bestemmiando parole di libertà.
Non ignorava Garibaldi l'ardore con che ambedue si sarebbero
egualmente lanciati sulle di lui tracce, e perciò affine di meglio celar
loro e la propria situazione e le sue mire, aveva diviso in molti piccoli
drappelli le sue genti che spinse in direzioni diverse, mostrandosi
così nel tempo medesimo in disparatissimi punti. Per lo che i nemici,
francesi ed austriaci, quantunque in numero di gran lunga superiore,
mal sapendo ove rivolgersi per coglierlo, vedevansi obbligati ad
errare alla ventura, e con inutili marcie stancare i propri soldati, che
talora quando meno vi s'attendevano, sentivansi improvvisamente
colpiti dai tiri d'un nemico, di cui non trovavan più orma. Con questo
incessante avvicendarsi di marcie e di inseguimenti erasi condotto in
Toscana, coll'intendimento di tentare anche quelle popolazioni e
conoscerne l'animo. Apparve perciò nelle vicinanze di Montepulciano
verso il 10 di luglio, e sostò per prendervi riposo sull'alpestre monte
Fallonico, ove era impossibile al nemico l'avvicinarglisi. Entrò più
tardi in quella città, ove da un convento di frati furongli tratti alcuni
tiri di fucile; la qual cosa diede luogo a che Garibaldi ritenesse presso
di sè e conducesseli fuori, e il sottoprefetto ed alcuni preti di quel
paese, i quali rilasciò poi subito, senza ulteriormente occuparsi nè di
loro nè dei frati.
Accennando da Montepulciano alla volta d'Arezzo, stavano in
quest'ultima città e nella stessa Firenze in allarme gli uomini della
ristorazione, e l'italiana Arezzo vide le sue porte chiudersi
all'avvicinarsi di Garibaldi, come se uno straniero nemico o un
malfattore la minacciasse. Contro la quale condotta protestarono in
modo solenne il popolo e gli abitanti di quei dintorni, i quali
affrettaronsi numerosi a salutare i fratelli ed a recar loro il
bisognevole, onde potessero ristorarsi della fame e della sete patite
in que' lunghi travagli.
Erano in que' momenti le condizioni d'Italia tutta, e di Europa, poco
o nulla favorevoli alla causa della libertà, perciò i popoli non potendo
corrispondere agli eccitamenti di Garibaldi, stavano quieti, oppressi
dagli eserciti stranieri, accampati in gran numero nelle nostre
provincie. Fattosi persuaso Garibaldi della realtà dolorosa, per cui
doveva rimettere ai giorni avvenire il compimento del magnanimo
proposito rifaceva i passi, avviandosi verso l'Umbria. Anche durante
quella ritirata ebbe sempre ai fianchi l'austriaco, che inseguivalo
numeroso e senza prender mai posa. Marcie e contromarcie
precipitose e continue, riposi brevi, e conturbati sempre dal pensiero
d'un attacco imminente, vigilanza diligentissima, corse per luoghi
alpestri e tenuti per impraticabili; talora circondati dal nemico, che
stava per serrarli nella vasta cerchia, che facevasi ad ognora più
stretta, e con volte e rivolte sfuggirgli dalle mani, che già si
stendevano sopra di loro; tal altra lanciarsi arditamente tra mezzo
alle schiere nemiche, e transitare al punto bramato senza che
azzardassero offenderli. Per siffatte circostanze fu maravigliosa
quella ritirata verso gli stati romani, da dove Garibaldi risolveva
ricoverarsi finalmente in S. Marino, nella certezza di esservi ben
accolto.
La disciplina più rigorosa fu da Garibaldi fatta osservare dalle sue
truppe lungo questa escursione; a tale spinse lo scrupolo da quel
lato, che per lievi mancanze inflisse i più severi castighi. I luoghi per
cui transitò non ebbero che a lodarsi dell'ordine e del rispetto alle
persone e alle cose. Allorchè le vettovaglie mancavano, ei ricorreva
alle comuni che fornivangli l'occorrente, e giammai si fece lecito di
togliere da per se neppure lo strettamente necessario.
Molte volte i suoi uffiziali instarono presso di lui affine di indurlo a
battersi col nemico, ed egli consultando la difficile posizione in cui si
trovavano, e calcolato con maggior prudenza le cose, rifiutò
costantemente di farsi aggressore. Mancavangli i mezzi di trasporto
pei feriti, mancavagli un luogo sicuro ove depositarli: come mai
avrebbe egli potuto acconsentire in tanto critica condizione, che i di
lui compagni s'esponessero alle eventualità di una lotta, dalla quale
erasi convinto non poter più ricavare quei benefizi di che si era
lusingato dapprima?
Entrava quindi in S. Marino, ove il governo e gli abitanti facevangli
tutta quell'onorevole e lieta accoglienza che si doveva a fratelli. Quivi
chiamati a sè gli uffiziali, rendeva lor noto essere oramai inutile
continuare nell'intrapresa, e necessario quindi lo sciogliersi, e
provvedere ciascuno alla propria salute in quella terra amica.
Frattanto l'austriaco avea per mezzo del governo di S. Marino fatto
proporre a Garibaldi una capitolazione, colla quale era offerto libero
il campo per ritirarsi al proprio paese ad ognuno della sua colonna,
ed assicurato a lui un passaggio per l'America. Concertato col
reggente di S. Marino il modo di salvare i compagni, rifiutò per sè
ogni patto dell'austriaco, cui non volle umiliarsi.
Non rimanendo in Italia più altro campo ove si combattesse contro lo
straniero, tranne Venezia, ei concepì lo ardito divisamento di recarsi
a far le ultime prove nell'eroica città, che oramai sola sosteneva la
bandiera italiana colla guerra. Perciò accompagnato dalla moglie che
da Roma avevalo voluto seguire ad ogni costo, e da un centinaio
d'uomini i quali in onta a tutto non seppero risolversi ad
abbandonarlo, scese dalla montagna di S. Marino alle pianure del
Cesenatico, ove stavano a vigile guardia numerosi gli austriaci, più
che mai bramosi di averlo nelle mani. Mercè la scorta di generosi
patriotti di quei dintorni potè la piccola brigata passare non vista in
mezzo ai nemici, e giungere alla sponda senza verun ostacolo. Solo
non ebbe amica la fortuna quel santo martire, il quale smarritosi
nella corsa cadde in potere del nemico, e più tardi spirò in Bologna
rotto dai piombi tedeschi stromenti dell'ira clericale. Perdita che
lasciò un immenso dolore nell'animo di Garibaldi che nel P. Bassi
venerava il vero tipo dell'uomo di Dio.
Era questa la terza volta che egli veniva colpito nella parte più
sensibile del suo cuore dacchè aveva riveduto la patria. Fin dai primi
giorni del suo approdo in Genova la morte ponendo fine al martirio
di una troppo lunga infermità, avevagli rapito l'antico fratello d'armi,
il colonnello Anzani, al quale stringevalo stima ed affetto caldissimo.
Combattendo sotto le mura di Roma contro i Francesi erasi veduto
orbare d'un altro a lui estremamente caro per valore e per senno
militare, il colonnello Masina di Bologna. Pareva che un maligno
destino salvando a lui la vita da tanti e così fieri pericoli, volesse
fargliela misera ed insopportabile, accumulando sul di lui animo
dolori sopra dolori, che qui non ebbero ancor fine.
L'austriaco informato del rifiuto di Garibaldi per le condizioni
propostegli, emanò severissimi ordini contro chi avesse dato asilo a
lui e ai compagni, e come se l'atto già di per sè barbaro non fosse
bastante, un altro volle aggiungerne più barbaro ancora. Eragli noto
che la indivisibile compagna stavagli a fianco; — ed egli, il tedesco,
ricordavalo alle popolazioni, affinchè meglio fosse riconoscibile il
marito! e non si vergognava di avvertire inoltre come a più chiaro
indizio, che era la donna incinta da vari mesi. Lo stato dell'infelice
Anna, che per qualunque altro nemico sarebbe stato un titolo a
mitigare i feroci diritti della guerra, doveva servire invece
coll'austriaco a fare più desolata e lagrimevole la condizione di lei!
Tali sono gli uomini che pesano sulla nostra sventurata patria!
Ma il bando assassino dello straniero non metteva punto sgomento
nel cuore di quei generosi abitanti, poichè non solo ebbero i fuggitivi
fraterna accoglienza dovunque, ma trovarono sulla riva pronti i
pescherecci bragozzi che li accolsero e li condussero lontano.
Rivedendo il mare, e sentendolo fremere intorno a sè, quasi fosse la
cara voce d'un amico, esultava Garibaldi tra i buffi del vento che
venivano a scompigliarli sulla fronte i lunghi capegli; e navigando alla
volta di Venezia sentiva ognora più rinfrancarsi l'animo al pensare,
che tra non molto avrebbe potuto toccare la terra desiderata e forse
operare ancora qualche bel fatto che il suo nome non solo
illustrasse, ma, ciò che più stavagli a cuore, al nome italiano fosse
onorevole, e alla causa della libertà di giovamento. E l'ardore e la
straordinaria concitazione dell'animo suo ei comunicava ai compagni
stimolandoli colla seducente pittura de' nuovi pericoli e delle più
splendide glorie.
Così viaggiando tutta una notte erano sull'albeggiare pervenuti
all'altura di Comacchio, allorquando vedevansi sorgere dinanzi, e non
molto da loro discosto, i legni da guerra austriaci veglianti in quelle
acque, e senza alcun dubbio attendendoli. Appena scoperti furongli
rivolti sopra i cannoni, che incominciarono a bersagliarli fieramente;
in breve alcuni bragozzi andarono capovolti perendo miseramente le
persone, altri furono raggiunti e fatti prigioni; solo, per quanto ci
consta, pervenne Garibaldi a riguadagnare la costa col suo
palischermo. Forse alla sua rara abilità di marino, alla robustezza del
braccio, e al raro suo sangue freddo, ch'egli conserva sempre
inalterato anche ne' momenti d'estremo pericolo, o forse al volere
della Provvidenza che lo riserba al compimento di qualche alta
impresa, è dovuto se in tale emergenza potè sottrarsi agli
inseguitori.
Toccava finalmente la spiaggia; ma ivi la sua costanza ed il suo
valore dovevano trovarsi alla più tremenda prova, che mai padre e
marito possano sopportare. Tante corse affannose pe' monti tanti
giorni e notti senza prendere riposo, e lo sgomento continuo
nell'animo per la sorte del marito, e le privazioni d'ogni cosa al di lei
stato indispensabile, e l'incontro fatale sul mare, tutto aveva
contribuito a spossare le robuste forze della infelice sua donna, e a
condurla a termini di morte. Al toccare la riva appena rimaneva alla
sventurata un tenue alito di vita — Era quel luogo deserto; e nessun
soccorso poteva venirle apprestato. Più tardi apparve qualcheduno
cui Garibaldi mandò in fretta a Ravenna per un medico; ed inoltre
potè dalla pietà di quelle genti ottenere un biroccio, sul quale adagiò
la morente, che condusse nella casa d'un contadino, in una terra del
marchese Guiccioli, non molto lontana dal mare.
La povera famigliuola che l'abitava commossa a tanta sventura di
quegli sconosciuti offrì un letto per la donna moribonda —
Sventurato! appena Garibaldi ebbe tempo di coricarla, che già la
travagliata aveva finito di patire!
Quel colpo atterrò l'animo di colui che aveva tante volte nei suoi
giorni sentito senza punto commoversi ruggire intorno a sè la
desolazione e la morte — Chinò il capo come cedendo al peso di così
grande dolore; poi chiesto un bicchier d'acqua per mitigare l'arsura
che stringevalo alle fauci, ed alzato lo sguardo al cielo, quasi
invocandolo a testimonio di quanto pativa per la causa dell'umanità,
e dato un ultimo doloroso addio alla fredda spoglia della amata sua
donna, uscì frettoloso da quella casa e disparve.
Povera Anna! Ella che soleva con tanto amore visitare in America la
sepoltura d'una sua figliuoletta, che Dio le tolse, e volle tra i suoi
angeli, e con quell'affetto istesso con cui s'affaccendava a renderla
vaga e lieta d'ornamenti in vita, davasi continua cura perchè il
sepolcro ch'avevala accolta paresse men tristo, e desse
testimonianza d'un amore che durava oltre la fossa, povera Anna!
era gran mercè se la cristiana carità del buon contadino che avevala
ospitata, poteva dar riposo alle sue ossa in un campo ignorato,
senza che un segno le indicasse alla pietà de' suoi cari, o alla
reverenza di quanti hanno in pregio tanta virtù e tanto amore di
sposa!
Ma quelle ossa non poterono aver pace! chè

La derelitta cagna ramingando

sconvolse quella terra, che le copriva, e svelò all'inquisizione


dell'austriaco la colpa del povero contadino, il quale convinto d'aver
dato ricetto in vita e poi sepoltura a quella morta, fu da que' feroci
messo in carcere!
All'uscire dall'infausta casa, Garibaldi aveva seco un suo fido,
capitano Leggero di Sardegna, il quale d'America era venuto con lui
a prender parte alla guerra nazionale. Accompagnato da questi,
pensò guadagnare lo stato sardo, unico luogo in Italia, in cui poteva
sperare tranquillità e sicurezza; ma il cammino era difficile e lungo,
tutti gli stati romani da quel lato erano occupati dagli austriaci, la
Toscana medesima erane ingombra, pure fidando in Dio e nella sua
stella s'accinse al periglioso viaggio.
Ignoravasi dovunque la sorte toccata all'uomo che aveva con sè
l'amore di tutti: non v'era patriotta in Italia che trepidante non ne
chiedesse novella: erasi sparsa la voce che avesse approdato in
Venezia, e fu questa una pietosa invenzione per eludere l'austriaca
vigilanza; in Venezia stessa era stato annunciato imminente il di lui
arrivo, ma fra l'incertezza di queste voci tutti perdevansi in
conghietture, e facevano voti per la salvezza d'un tant'uomo: la
speranza di saperlo fra non molto fuori d'ogni pericolo albergava nel
cuore di tutti i buoni, ma talora le liete speranze veniva a troncarle il
lungo silenzio e il non udirne mai nuova.
Frattanto egli imbattutosi in uomini pei quali la patria è una sacra
parola, aveva in essi trovato appoggio ed asilo fraterno; molti giorni
rimase celato in luogo, che non crediamo ancora fuori di pericolo per
que' generosi il rendere noto; di là scortato sempre da qualche fido
da uno in altro punto veniva lentamente avvicinandosi: sovente
ozioso nel giorno, e ricovrato ne' boschi aspettò il favore della notte
per continuare il viaggio, talora incalzato dagli eventi s'aggirò tra le
file dei nemici, mentre forse stavano meditando in qual modo
avrebberlo potuto raggiungere; altra volta mentre seduto in una
osteria attendeva a rifocillarsi, capitò, e s'assise accanto a lui il
croato, che senza sospetto vide quello sconosciuto alzarsi e partire.
Dovunque egli trovò ardenti e coraggiosi patriotti, che per lui non
badarono a pericoli nè a fatiche; e sappiamo d'un parroco il di cui
nome aspettiamo tempi men tristi per segnalare alla riconoscenza di
tutta Italia, il quale confortò l'illustre fuggiasco di tutte quelle
amorevoli cure, che soltanto sa suggerire un nobile animo, educato
alla sublime dottrina del Vangelo.
Finalmente dopo tanto errare, dopo tante dolorose vicende rivedeva
la marina dalla costa toscana. Novello Mario inseguito da crudeli
nemici e colla morte ruggente alle spalle, egli pure dalla spiaggia
tendeva lo sguardo sulle onde in traccia d'una vela, che il
raccogliesse, e come Mario ei vedeva una barca propizia a suoi voti
approssimarsi alla riva ed accoglierlo nel suo seno: ma del fuggiasco
romano più fortunato egli trovava cuori generosi, che lungi dallo
spaventarsi all'apprenderne il nome, vogarono più lieti alla costa
sarda, superbi di poter salvare un tant'uomo.
Era il 5 di settembre, ed il giorno trentacinquesimo del travaglioso
viaggio, allorquando la barca guidata da pescatori, raccoglieva la
vela sulla rada di Porto Venere. Garibaldi aveva unicamente tre lire in
suo potere! e male ei quindi poteva rimunerare a danaro i suoi
salvatori, cui diede unica ricompensa un'abbraccio, che que' buoni
popolani accolsero colle lagrime agli occhi, e uno scritto, che renderà
fede ai futuri della sua riconoscenza per tanto benefizio.
Ricevuto in Porto Venere con segni di manifesta reverenza e d'amore
dal popolo, ebbe da un amico i mezzi per recarsi a Chiavari, ove
appena arrivato, il governo per mezzo de' suoi agenti s'impadronì di
lui, e fecelo scortare coi carabinieri a Genova, ritenendolo ivi
custodito nel palazzo ducale.
Il Parlamento appena conosciuto il reo procedere del ministero
contro un cittadino, che aveva pur tanti diritti non solo ad
un'accoglienza amorevole per le sue sventure, ma al rispetto e ad
ogni onorifica dimostranza per quanto aveva operato in pro della
patria comune, biasimò altamente ed a gran maggioranza di voti
quello scandaloso contegno, adottando il seguente ordine del giorno,
che noi riferiamo ad encomio dei nobili sentimenti e dell'indignazione
generosa, manifestati nella tornata del 20 settembre dai
rappresentanti nazionali. «La Camera dichiarando che l'arresto del
generale Garibaldi e la minacciata espulsione di lui dal Piemonte
sono lesivi dei diritti conservati dallo Statuto e dei sentimenti della
nazionalità italiana passa all'ordine del giorno.»
In onta del quale Garibaldi continuò ad essere sostenuto in prigione,
ove molti fra i più ragguardevoli uomini che trovavansi in Genova, e
gli uffiziali del presidio affollavansi ogni giorno a visitarlo. Non mai
uscì dalla sua bocca un lamento intorno a quel modo d'agire verso di
lui, sembrava non accorgersi, o non dare alcuna importanza a quel
passeggero capriccio della nemica fortuna. A quanti l'avvicinarono in
quei giorni, egli non d'altro parlò che dell'avvenire d'Italia,
confortandoli ad aver fede e ad unirsi concordi per la guerra
nazionale, nè lontana, nè perduta, affine di raggiungere la bramata
vittoria. Quegli stessi che prevenuti contro di lui andarono a vederlo
per mera curiosità, ne partirono compenetrati d'un senso
d'ammirazione, se non d'affetto.
Quanti altri che formano attualmente i più bei titoli che abbia l'Italia
alla stima delle nazioni sono, com'era, ed è in parte tuttavia
Garibaldi, calunniati, e costringerebbero in egual modo i loro nemici
a ricredersi ed a stimarli, se fossero ben conosciuti!
Desiderando Garibaldi rivedere la vecchia madre in Nizza ed i figli,
consentì il governo che v'andasse sopra un vapore: si disse che un
agente di polizia in incognito lo accompagnasse. È impossibile
descrivere l'entusiasmo del popolo nicese al rivedere il suo
concittadino dopo tante avventure e dopo i fatti di Roma.
Trattenutosi colà appena il tempo necessario per visitare i parenti e
gli amici, risaliva a bordo del vapore per tornare a Genova, giusta la
data parola, e mettersi nuovamente alla disposizione del governo. Il
quale fermo nell'allontanarlo dallo Stato, alcuni giorni dopo fecelo
trasportare con un vapore da guerra a Tunisi, avendo Garibaldi scelto
per luogo della sua dimora quell'affricana città, venutigli forse in
dispetto cotestoro della civile Europa, che con atti da veri barbari
toglievano ai popoli la libertà, bombardavano città innocenti
vantandosene liberatori, e procedevano tant'oltre da perseguitare
perfino un individuo, solo ed inerme, e scampato per miracolo da
tanti e così gravi pericoli.
Nel suo tragitto da Genova alla volta di Barberia, il vapore che lo
conduceva approdò in Cagliari, ove la popolazione appena informata
della sorte di Garibaldi s'affollò numerosissima sulle barchette, spinta
dal desiderio di vedere almeno una volta quell'uomo di cui avevano
udito tante nobili e maravigliose imprese. I fieri isolani, nelle cui
vene scorre ardente il sangue latino, fecero ripetute volte echeggiare
quelle sponde agli evviva al forte Italiano, e agli auguri di più lieta
fortuna in non lontano avvenire — Era quello un ultimo addio, che
l'Italia mandava al prode guerriero dall'estremo suo lembo — E
quell'addio si prolungava sulle acque del golfo, come grido di madre
desolata che vede strapparsi dal seno il prediletto suo figlio.
Salpato poco dopo per Tunisi arrivava in quel porto il giorno 21 di
settembre; ma anche là attendevalo la vendetta francese e la
persecuzione del governo sardo, se è vera la voce che ne corse [13].
Il Bey cedendo alle esigenze della grande nazione che non poteva
vivere tranquilla se quell'uomo avesse avuto stanza in Barberia, negò
il permesso a Garibaldi di sbarcare nella sua città. E al medesimo
tempo quasi avesse voluto manifestargli l'animo suo non avverso, e
forse anco a scusa del rifiuto impostogli dal più forte, il Bey gli offerì
un vapore perchè si recasse a Malta, ove fosse piaciuto a Garibaldi
trasferirvisi.
Simile anche in ciò a Mario, che fuggitivo dalle coste d'Italia si rivolse
a quell'istesso porto, non molto discosto dal quale sedeva l'antica
Cartagine, e dovette subito allontanarsene riprendendo nuovamente
il mare per sottrarsi alle persecuzioni de' suoi concittadini e de'
barbari, Garibaldi tornò indietro colla stessa nave, dal comandante
della quale fu sbarcato nella piccola isola di Maddalena, collocata
presso la costa settentrionale della Sardegna, ed ivi lasciato sotto la
custodia del comandante militare del luogo, fino a che il governo
avesse preso nuove determinazioni.
Quell'isoletta fu per Garibaldi l'oasi invocata dal viaggiatore affranto
dalle lunghe e perigliose fatiche del deserto, sconvolto da fierissimi
venti. Ivi trovò riposo, e volti amici e cuori che fecero sue le di lui
pene. — Tutti quegli abitanti andarono a gara per testimoniargli
l'interesse e la stima che sentivano per lui. Dal più ricco al più povero
nessuno tra i buoni isolani lasciò di stringere quella mano che aveva
sì fieramente percosso i nemici d'Italia; tanto essi l'amavano, tanta
confidenza aveva egli ispirata col suo fare semplice e cordiale! —
Crediamo dover nostro di specialmente rammentare qui a titolo
d'onore il signor Susini sindaco nell'isoletta, padre di quell'istesso
Susini, scelto da Garibaldi a suo successore nel comando della
legione italiana in Montevideo, da cui il nostro amico ebbe le più
distinte prove di affettuosa amicizia.
Nei molti giorni, che quasi dimenticato rimase colà, ei soleva per
allontanare da sè la cupa malinconia, da cui era tormentato,
esercitare il corpo e distrarre la mente colla caccia e la pesca, di lui
prediletti passatempi. E un giorno mentre egli era in riva al mare
vide un burchiello a vela navigare lungo la costa con evidente
pericolo di capovolgersi, soffiando impetuoso il vento; nè s'ingannò,
che poco dopo cresciuto questo in forza e fattosi più turgido il seno
della vela, non presentando l'esile barchetta sufficiente peso a
mantenere l'equilibrio, si piegò rovesciandosi sulle acque. A quella
vista non rimase Garibaldi freddo spettatore; si precipitò nel mare
seguito da un suo compagno, e tanto s'adoperò colle robuste
membra e coll'ingegno, che que' naviganti furono salvati. Così la
Provvidenza diede a lui occasione di mostrare agli amorevoli suoi
ospiti in qual guisa ei paghi i debiti di gratitudine.
Non consentendo il governo ch'egli rimanesse più a lungo nel
territorio sardo, fecelo trasportare dal brigantino il «Colombo» a
Gibilterra, unico luogo ove potesse recarsi tra i più vicini in Europa.
Al suo arrivo colà ebbe l'assenso del governatore soltanto per
isbarcarvi e rimanervi pochi giorni. Richiesto il Console spagnuolo se
sarebbe accolto in qualche punto della Spagna, n'ebbe risposta
negativa — Andare in Francia non era cosa che potesse venirgli in
mente. A fronte di tante turpitudini, il Console degli Stati Uniti
d'America e con lui gli uffiziali delle sue navi da guerra, quasi a
protestare contro tanta infamia per l'onore dell'umanità, si
presentarono ad offrire al valent'uomo perseguitato dai vermi della
diplomazia, oro, asilo nel loro paese, e un legno da guerra per
trasportarvelo — Garibaldi non volendo allontanarsi d'Europa
ringraziò que' nobili figli della libera America, e preferì tentare di
nuovo l'Affrica. Partì pochi giorni dopo per Tangeri, nell'impero di
Marocco, ove fu accolto da persona amica, e trovò quel pacifico asilo
che invano aveva desiderato in patria.
All'apprendere questi fatti i posteri maraviglieranno senza dubbio per
tanta ingratitudine verso un così illustre cittadino, e chiederanno
indignati se le proteste d'amore alla causa italiana e alla libertà tanto
spesso ripetute ai dì nostri da certi individui, fossero un'ironia gettata
in volto a un popolo di imbelli!
Tutta la vita di Garibaldi è un continuo e non infecondo sacrifizio alla
libertà e alla patria. Nei suoi atti d'uomo privato, come in quelli
d'uomo pubblico, ne' lieti convegni degli amici, come nelle serie e
gravi adunanze, uno fu sempre l'oggetto ch'ebbe in mira, uno
l'argomento dei suoi pensieri e de' suoi discorsi: Patria e Umanità.
Le sublimi aspirazioni della forte anima sua costantemente
s'elevarono a quell'altissimo concetto; di ogni altra cosa poco o nulla
prese mai cura, perciò fu visto combattere sempre, e la causa
americana difendere con quell'ardore medesimo con cui impugnò le
armi in Lombardia ed in Roma — Al pensiero tenne sempre dietro e
incessante l'azione.
Convinto che soprattutto l'Italia ha bisogno di riabilitarsi nell'opinione
del mondo con forti e magnanimi fatti, e che la libertà, come il pane,
dev'essere acquistata col sudore della propria fronte, egli vuol
combattere solo co' suoi le italiane battaglie, e respinge come uno
sfregio all'onore nazionale, e una macchia che rimarrebbe eterna
nella storia d'Italia, ogni idea d'intervento straniero. L'Italia deve, e
volendo può fare da sè, glielo impone il suo passato, lo esige
l'altezza della sua missione avvenire. Lo schiavo ognor fremente, e in
continua lotta virilmente sostenuta è per lui la più sublime protesta
dell'uomo conscio della propria dignità; quegli che infingardo o
fiaccamente operando invoca, e accetta sollievo dalla carità altrui lo
muove a sdegno e disprezzo. Ei vorrebbe prolungata la schiavitù
della patria, anzi che averla libera per mano straniera. Spezzerebbe
la sua spada, e tra i ferri nemici cercherebbe la morte se all'Italia
fosse riserbata quell'onta.
Uomo dell'Umanità, ei vagheggia nell'avvenire la fratellanza dei
popoli, ma al banchetto delle nazioni ei vuol sedere da eguale, o non
sedere. Può l'Italia dalla sua altezza discendere come l'uomo Dio
nelle tenebre del sepolcro, ma come l'Uomo Dio deve risorgere per
sua propria virtù — Grande sovra tutte le nazioni nel passato, deve
esserlo nell'avvenire; l'esempio altrui male s'attaglia a chi esce dalla
sfera comune.
Educato fin dai primi suoi anni ai principii delle libertà popolari e
convinto che a raggiungere l'altezza de' suoi destini l'Italia deve in
un futuro più o meno lontano essere una, ogni suo pensiero ed ogni
suo atto concernente alla Patria, fu sempre diretto a quelle due mire;
ma conscio egualmente che anzi tutto denno gl'Italiani acquistarsi
l'indipendenza, egli, come tutti i suoi fratelli di fede politica [14], è
pronto, messa a parte ogni individuale convinzione, a far sua la
bandiera di colui, che offrendo maggior probabilità di riuscita,
entrerà in campo irrevocabilmente deciso a cacciare oltr'alpe
l'austriaco.
Garibaldi conta oggi 42 anni d'età. La stessa energia e l'ardore
medesimo della prima gioventù governano tuttora quell'anima
indomata. Il suo discorso breve, e d'ordinario pacato, s'infiamma, e
dai suoi occhi scintilla un insolito splendore quando parla di patria e
di gloria nazionale. Austero nei costumi, parco nel dar lodi, dal suo
labbro non esce mai detto che offenda; delle offese ricevute non
degna mover lamento e le obblia. Inesorabile nel suo sdegno verso i
codardi ed i tristi, è indulgente co' valorosi.
Senza alterigia, come senz'umiltà, tratta con egual rispetto chiunque;
il semplice soldato come ogn'altro ha sempre libero accesso a lui;
pari all'ultimo de' suoi nel cibo, nel vestire e nelle privazioni della vita
militare, si distingue soltanto per l'aspetto decoroso e la reverenza
che nessuno sa negargli. Quanti l'avvicinarono gli rimasero amici: i
suoi compagni d'armi ebbero sempre per lui affetto di figli. Allorchè
un doloroso pensiero gli travaglia l'animo, ei suole calarsi sulla fronte
il berretto e starsi o passeggiare solo e taciturno; ha il passo non
greve, ma lento, e l'andare composto a gravità senz'ombra di studio.
Per lo più serio e sopra pensieri, la vista d'un amico lo allegra e
chiama il sorriso sulle di lui labbra. Fra persone di sua intimità talora
s'abbandona allo scherzo, ma per poco, quasi l'assalisse rimorso
d'aver sprecato il tempo. — Riverente alla madre, ottimo marito, è
co' figli or sorridente, ora severo.
I tanti travagli durati per la propria patria e l'altrui gli hanno fruttato
povertà, persecuzioni, un nome onorato in Europa e in America [15],
l'odio dei tristi e l'amore del suo paese, di cui forma una delle più
splendide glorie. Lasciò in Nizza la vecchia madre, coi tre figli,
Menotti, Ricciotti e Teresita, all'educazione de' quali provvede con
affetto di padre l'avvocato Garibaldi cugino del Generale: — egli, il
suo amico Daideri, e non altri.
Uomini generosi, di cui non è difetto la Dio mercè in Italia, offersero
al prode uomo ragguardevoli somme, che non accettò. D'indole
laboriosa, egli trova dovunque come sostentarsi coll'opera sua;
all'uopo non esiterebbe un solo momento a imbarcarsi per semplice
marinaio. Sobrio, modesto, e tollerante le fatiche, poco gli basta.
Accettò con lieto animo una spada superbamente lavorata in Firenze,
frutto d'una soscrizione nazionale. Un'altra eseguita dall'egregio
artista Borani in Torino, dono essa pure de' suoi compatrioti, sarà tra
non molto depositata nella sua casa materna.
Di queste spade una rappresenta nell'impugnatura l'Italia, che
appoggiata al brando attende a ristorare le proprie forze.
Dio le infonda vigore! Quando l'ora di sollevarlo nuovamente sarà
giunta, Garibaldi nol lascerà giacere ozioso. Dalle aride montagne di
Marocco, donde mirando all'Italia, medita la grande vendetta,
tornerà fulmine di guerra, a dar nuove glorie alla patria, nuovi
argomenti d'odio ai malvagi, e, Dio confermi l'augurio, l'ultimo colpo
all'austriaco fuggente oltre l'Alpi!
FINE.
NOTE:

1. Nel 1831 trovandosi Garibaldi in Taganrok capitò in una locanda,


ov'eransi riuniti molti marini di varie parti d'Italia, i quali delle umilianti
condizioni di questa avevan fatto doloroso argomento ai loro discorsi.
Era tra costoro un giovane, il credente, a cui Garibaldi allude, il quale
affannavasi a far concepire ai poco creduli compagni speranze di lieto e
glorioso avvenire alla patria comune. Garibaldi dal fondo della sala
porgeva attento l'orecchio a quel ragionare; e alla fine non potendo più
trattenersi correva verso lo sconosciuto giovane e, col trasporto che ben
manifestava l'ardore dell'animo stringevalo al suo seno. Da quel giorno
ei divenne l'amico del cuore di quel credente, che lo iniziò alle dottrine
della Giovine Italia.

2. Vedi dal n. 9, 11, al 16.

3. Vedi Corr. Liv., numeri citati, nei quali è diffusamente narrato questo
fatto.

4. Erano appunto sei mesi dacchè Garibaldi era stato dal governo incaricato
della spedizione al Salto.

5. Queste parole dell'ammiraglio francese non possono far allusione che


alle ripetute calunnie a carico degl'Italiani apparse ne' giornali francesi
intorno all'occupazione della Colonia, e specialmente ad articoli
pubblicati nella Presse, generalmente attribuiti al signor Page,
comandante del brigantino Ducoëdic, il quale trovavasi dinanzi alla
Colonia all'epoca dell'occupazione suddetta, e traeva coi cannoni
sugl'Italiani sbarcati, in luogo di mitragliare i nemici. — Il signor Page è
tenuto nel Rio de la Plata come interessato partigiano di Rosas.
Era ministro di Francia in Montevideo il barone Deffaudis.

6. Vedi: Réponse aux détracteurs de Montevideo par M. Pacheco y Obes,


Paris 1849.

7. Réponse aux détracteurs de Montevideo par M. Pacheco y Obes, già


citato.
8. Fra i molti che splendidamente contribuirono a formare la somma
necessaria, si distinse il signor Stefano Antonini, negoziante di Genova,
che sborsò la non tenue quantità di 30,000 lire e più onde favorire la
nobile intrapresa. Nella storia della Legione italiana in Montevideo
dovrebbe essere pubblicata la lista di tutti i contribuenti a quella
spedizione.

9. Fra questi ultimi merita speciale menzione Francesco Gaggini, il quale


dopo venti e più anni d'assenza dalla patria, abbandonava ad un tratto i
suoi ben avviati commerci per venire a combattere in Italia, e
accompagnava Garibaldi fino al momento, in cui disciolta la Legione in S.
Marino, ciascheduno doveva provvedere alla propria salvezza.

10. Specie di mantello usato nelle campagne dei paesi del Rio de la Plata ed
altri luoghi dell'America meridionale.

11. Siège de Rome par B. Del Vecchio.

12. L'esercito francese montava a 40,000; gl'Italiani sommavano appena a


12,000 di truppe regolari.

13. Fu detto, che il Console francese in Tunisi d'accordo col sardo facesse
vive istanze presso il Bey, onde Garibaldi venisse respinto; e che il
secondo inviasse poi persona del Consolato a bordo del Tripoli con
incarico di far presente a Garibaldi che egli, il Console erasi adoperato
presso quel Governo affinchè gli accordasse la bramata ospitalità!

14. V. Mazzini, Italia del Popolo. — Vol. II, pag. 23 — gennaio 1850.

15. Nell'America del Nord quattro anni or sono vide la luce un romanzo
intitolato Dolores nel quale a Garibaldi è assegnata una nobile parte. —
Noi rammentiamo questo lavoro del nostro amico Harro Harring ad
encomio dell'autore e di Garibaldi.

You might also like