diff options
author | Fred Drake <fdrake@acm.org> | 2001-08-28 14:56:05 (GMT) |
---|---|---|
committer | Fred Drake <fdrake@acm.org> | 2001-08-28 14:56:05 (GMT) |
commit | d800cff80de4a2e8e9d294866da625cc27c538b9 (patch) | |
tree | 6a769c2fba96f688d4064b0c347493b0190ec506 /Doc | |
parent | 49a806edbb298f2a5be3598bd80c21392cb6968d (diff) | |
download | cpython-d800cff80de4a2e8e9d294866da625cc27c538b9.zip cpython-d800cff80de4a2e8e9d294866da625cc27c538b9.tar.gz cpython-d800cff80de4a2e8e9d294866da625cc27c538b9.tar.bz2 |
Added explanation that [...] * n generates shallow copies of [...], so
the contents will be shared by multiple references.
This closes SF bug #455694.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/lib/libstdtypes.tex | 28 |
1 files changed, 26 insertions, 2 deletions
diff --git a/Doc/lib/libstdtypes.tex b/Doc/lib/libstdtypes.tex index 4949e60..5815f8c 100644 --- a/Doc/lib/libstdtypes.tex +++ b/Doc/lib/libstdtypes.tex @@ -416,7 +416,7 @@ and \var{j} are integers: equal to \var{x}, else \code{1}}{} \hline \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{} - \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{(1)} + \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} shallow copies of \var{s} concatenated}{(1)} \hline \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(2)} \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(2), (3)} @@ -442,7 +442,31 @@ Notes: \begin{description} \item[(1)] Values of \var{n} less than \code{0} are treated as \code{0} (which yields an empty sequence of the same type as - \var{s}). + \var{s}). Note also that the copies are shallow; nested structures + are not copied. This often haunts new Python programmers; consider: + +\begin{verbatim} +>>> lists = [[]] * 3 +>>> lists +[[], [], []] +>>> lists[0].append(3) +>>> lists +[[3], [3], [3]] +\end{verbatim} + + What has happened is that \code{lists} is a list containing three + copies of the list \code{[[]]} (a one-element list containing an + empty list), but the contained list is shared by each copy. You can + create a list of different lists this way: + +\begin{verbatim} +>>> lists = [[] for i in range(3)] +>>> lists[0].append(3) +>>> lists[1].append(5) +>>> lists[2].append(7) +>>> lists +[[3], [5], [7]] +\end{verbatim} \item[(2)] If \var{i} or \var{j} is negative, the index is relative to the end of the string: \code{len(\var{s}) + \var{i}} or |