Source

JythonBook / html / chapter2.html

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Chapter 2: Data Types and Referencing &mdash; Jython Book v0.1 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '0.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="Jython Book v0.1 documentation" href="index.html" />
    <link rel="next" title="Chapter 3: Operators, Expressions, and Program Flow" href="chapter3.html" />
    <link rel="prev" title="Chapter 1: Language and Syntax" href="chapter1.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="chapter3.html" title="Chapter 3: Operators, Expressions, and Program Flow"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="chapter1.html" title="Chapter 1: Language and Syntax"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Jython Book v0.1 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="chapter-2-data-types-and-referencing">
<h1>Chapter 2: Data Types and Referencing<a class="headerlink" href="#chapter-2-data-types-and-referencing" title="Permalink to this headline"></a></h1>
<p>We all know that programming languages and applications need data.  We define applications to work with data,
and we need to have containers that can be used to hold it.  This chapter is all about defining containers and
using them to work with application data.  This is the foundation of any programming language...it is how we get
tasks accomplished.  Whether the data we are using is coming from a keyboard entry or if we are working with a
database, there needs to be a way to temporarily store it in our programs so that it can be manipulated and used.
Once we&#8217;re done working with the data then these temporary containers can be destroyed in order to make room for new constructs.</p>
<p>We&#8217;ll start by taking a look at the different data types that are offered by the Python language, and then we&#8217;ll
follow by discussing how to use that data once it has been collected and stored.  We will compare and contrast the
different types of structures that we have in our arsenal, and I&#8217;ll give some examples of which structures to use
for working with different types of data.  There are a multitude of tasks that can be accomplished through the use
of lists, dictionaries, and tuples and I will cover the majority of them.  Once you learn how to define and use these
structures, then we&#8217;ll talk a bit about what happens to them once they are no longer needed by our application.</p>
<p>Lets begin our journey into exploring data types and structures within the Python programming language...these are skills
that you will use in each and every practical Jython program.</p>
<div class="section" id="python-data-types">
<h2>Python Data Types<a class="headerlink" href="#python-data-types" title="Permalink to this headline"></a></h2>
<p>As we’ve discussed, there is a need to store and manipulate data within programs.  In order to do so then we must also
have the ability to create containers used to hold that data so that the program can use it.  The language needs to know
how to handle data once it is stored, and we can do that by assigning data type to our containers.  However, in Python
it is not a requirement to do so because the interpreter is able to determine which type of data we are storing in a dynamic fashion.</p>
<p>The following table lists each data type and gives a brief description of the characteristics that define each of them.</p>
<table border="1" class="docutils">
<colgroup>
<col width="11%" />
<col width="89%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Data Type</th>
<th class="head">Characteristics</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>None</td>
<td>NULL value object</td>
</tr>
<tr><td>Numeric</td>
<td>A data type used to hold numeric values of integer, decimal, float, complex, and long</td>
</tr>
<tr><td>Boolean</td>
<td>True or False value (also characterized as numeric values of 1 and 0 respectively)</td>
</tr>
<tr><td>Sequence</td>
<td>Includes the following types:  string, unicode string, basestring, xrange, list, tuple</td>
</tr>
<tr><td>Mapping</td>
<td>Includes the dictionary type</td>
</tr>
<tr><td>Set</td>
<td>Unordered collection of distinct objects; includes the following types:  set, frozenset</td>
</tr>
<tr><td>File</td>
<td>Used to make use of file system objects</td>
</tr>
<tr><td>Iterator</td>
<td>Allows for iteration over a container</td>
</tr>
</tbody>
</table>
<p>Table 2-1.  Python Data Types</p>
<p>Given all of that information and the example above, we need to know a way to declare a variable in the Python language.
You’ve seen some examples in the previous chapter, but here I will formally show how it is done.  Let’s take a look at some
examples of defining variables in the following lines of code.</p>
<div class="highlight-python"><pre># Defining a String
x = ‘Hello World’
x = “Hello World Two”

#  Defining a number
y = 10

#  Float
z = 8.75

# Complex
i = 8.07j</pre>
</div>
<p>An important point to note is that there really are no types in Jython.  Every object is an instance of a class.  Therefore,
in order to find the type of an object in Jython it is perfectly valid to write obj.__class__.</p>
<div class="highlight-python"><pre># Return the type of an object in Jython using __class__
&gt;&gt;&gt; a = 'Hello'
&gt;&gt;&gt; a.__class__
&lt;type 'str'&gt;</pre>
</div>
<div class="section" id="strings-and-string-methods">
<h3>Strings and String Methods<a class="headerlink" href="#strings-and-string-methods" title="Permalink to this headline"></a></h3>
<p>Strings are a special type within most programming languages because they are often used to manipulate data.  A string
in Python is a sequence of characters, which is immutable.  This is very important to know as it has a large impact on
the overall understanding of strings.  Once a string has been defined it cannot be changed.  However, there are a large
amount of string methods that can be used to manipulate the contents of a particular string.  Although we can manipulate
the contents, Python really gives us a manipulated copy of the string…the original string is left unchanged.</p>
<p>CPython and Jython treat strings a bit differently.  There are two types of string objects in CPython, these are known as
<em>Standard</em> strings and <em>Unicode</em> strings.  Standard strings contain 8-bit data, whereas Unicode strings are sequences of data
composed of 16-bit characters.  There is a lot of documentation available that specifically focuses on the differences between
the two types of strings, this reference will only cover the basics.  It is worth noting that Python contains an abstract string
type known as <em>basestring</em> so that it is possible to check any type of string to ensure that it is a string instance.</p>
<p>In Jython, there is only one string type.  The string type in Jython supports full two-byte Unicode characters and all functions
contained in the string module are Unicode-aware.  If the u’’ string modifier is specified, it is ignored by Jython.  It is also
worth noting that Jython uses character properties from the Java platform.  Therefore properties such as isupper and islower, which
we will discuss later in the section, are based upon the Java properties.</p>
<p>In remainder of this section we will go through each of the many string functions that are at our disposal.  These functions will
work on both Standard and Unicode strings.  As with many of the other features in Python and other programming languages, there are
often times more than one way to accomplish a task.  In the case of strings and string manipulation, this definitely holds true.
However, you will find that in most cases, although there are more than one way to do things, Python experts have added functions
which allow us to achieve better performing and easier to read code.  Sometimes one way to perform a task is better achieved by
utilizing a certain function in one case, and doing something different in another case.</p>
<p>The following table lists all of the string methods that have been built into the Python language as of the 2.5 release.  Since Python
is an evolving language, this list is sure to change in future releases.  Most often, additions to the language will be made, or
existing features are enhanced.  Following the table, I will give numerous examples of the methods and how they are used.  Although
I cannot provide an example of how each of these methods work (that would be a book in itself), they all function in the same manner
so it should be rather easy to pick up.</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="79%" />
<col width="2%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Method</th>
<th class="head">Description of Functionality</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>capitalize()</td>
<td>Capitalize string</td>
<td>&nbsp;</td>
</tr>
<tr><td>center(width[,fill])</td>
<td>Reposition string and provide optional padding filler character</td>
<td>&nbsp;</td>
</tr>
<tr><td>count(sub[,start[,end]])</td>
<td>Count the number of times the substring occurs within the string</td>
<td>&nbsp;</td>
</tr>
<tr><td>decode([encoding[,errors]])</td>
<td>Decodes and returns Unicode string</td>
<td>&nbsp;</td>
</tr>
<tr><td>encode([encoding[,errors]])</td>
<td>Produces an encoded version of a string</td>
<td>&nbsp;</td>
</tr>
<tr><td>endswith(suffix[,start[,end]])</td>
<td>Returns a boolean to state whether the string ends in a given pattern</td>
<td>&nbsp;</td>
</tr>
<tr><td>expandtabs([tabsize])</td>
<td>Converts tabs within a string into spaces</td>
<td>&nbsp;</td>
</tr>
<tr><td>find(sub[,start[,end]])</td>
<td>Returns the index of the position where the first occurrence of the given substring begins</td>
<td>&nbsp;</td>
</tr>
<tr><td>index(sub[,start[,end])</td>
<td>Returns the index of the position where the first occurrence of the given substring begins</td>
<td>&nbsp;</td>
</tr>
<tr><td>isalnum()</td>
<td>Returns a boolean to state whether the string contain both alphabetic and numeric characters</td>
<td>&nbsp;</td>
</tr>
<tr><td>isalpha()</td>
<td>Returns a boolean to state whether the string contains all alphabetic characters</td>
<td>&nbsp;</td>
</tr>
<tr><td>isdigit()</td>
<td>Returns a boolean to state whether the string contains all numeric characters</td>
<td>&nbsp;</td>
</tr>
<tr><td>islower()</td>
<td>Returns a boolean to state whether a string contains all lowercase characters</td>
<td>&nbsp;</td>
</tr>
<tr><td>isspace()</td>
<td>Returns a boolean to state whether the string consists of all whitespace</td>
<td>&nbsp;</td>
</tr>
<tr><td>istitle()</td>
<td>Returns a boolean to state whether the first character of each word in the string is capitalized</td>
<td>&nbsp;</td>
</tr>
<tr><td>isupper()</td>
<td>Returns a boolean to state whether all characters within the string are uppercase</td>
<td>&nbsp;</td>
</tr>
<tr><td>join(sequence)</td>
<td>Joins two strings by combining</td>
<td>&nbsp;</td>
</tr>
<tr><td>ljust(width[,fillchar])</td>
<td>Align the string to the left by width</td>
<td>&nbsp;</td>
</tr>
<tr><td>lower()</td>
<td>Converts all characters in the string to lowercase</td>
<td>&nbsp;</td>
</tr>
<tr><td>lstrip([chars])</td>
<td>Removes the first found characters in the string from the left that match the given characters.  Also removes whitespace from the left.</td>
<td>&nbsp;</td>
</tr>
<tr><td>partition(separator)</td>
<td>Partitions a string starting from the left using the provided separator</td>
<td>&nbsp;</td>
</tr>
<tr><td>replace(old,new[,count])</td>
<td>Replaces the portion of string given in <em>old</em> with the portion given in <em>new</em></td>
<td>&nbsp;</td>
</tr>
<tr><td>rfind(sub[,start[,end]])</td>
<td>Searches and finds the first occurrence of the given string</td>
<td>&nbsp;</td>
</tr>
<tr><td>rindex(sub[,start[,end]])</td>
<td>Searches and finds the first occurrence of the given string or returns an error</td>
<td>&nbsp;</td>
</tr>
<tr><td>rjust(width[,fillchar])</td>
<td>Align the string to the right by width</td>
<td>&nbsp;</td>
</tr>
<tr><td>rpartition(separator)</td>
<td>Partitions a string starting from the right using the provided separator object</td>
<td>&nbsp;</td>
</tr>
<tr><td>rsplit([separator[,maxsplit]])</td>
<td>Splits the string from the right side and uses the given separator as a delimiter</td>
<td>&nbsp;</td>
</tr>
<tr><td>rstrip([chars])</td>
<td>Removes the first found characters in the string from the right that match those given.  Also removes whitespace from the right.</td>
<td>&nbsp;</td>
</tr>
<tr><td>split([separator[,maxsplit]])</td>
<td>Splits the string and uses the given separator as a delimiter.</td>
<td>&nbsp;</td>
</tr>
<tr><td>splitlines([keepends])</td>
<td>Splits the string into a list of lines.  Keepends denotes if newline delimiters are removed.</td>
<td>&nbsp;</td>
</tr>
<tr><td>startswith(prefix[,start[,end]])</td>
<td>Returns a boolean to state whether the string starts with the given prefix</td>
<td>&nbsp;</td>
</tr>
<tr><td>strip([chars])</td>
<td>Removes the given characters from the string.</td>
<td>&nbsp;</td>
</tr>
<tr><td>swapcase()</td>
<td>Converts the case of each character in the string.</td>
<td>&nbsp;</td>
</tr>
<tr><td>title()</td>
<td>Returns the string with the first character in each word uppercase.</td>
<td>&nbsp;</td>
</tr>
<tr><td>translate(table[,deletechars])</td>
<td>Use the given character translation table to translate the string.</td>
<td>&nbsp;</td>
</tr>
<tr><td>upper()</td>
<td>Converts all of the characters in the string to lowercase.</td>
<td>&nbsp;</td>
</tr>
<tr><td>zfill(width)</td>
<td>Pads the string from the left with zeros for the specified width.</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Table 2-2.  String Methods</p>
<p>Now let’s take a look at some examples so that you get an idea of how to use the string methods.  As stated previously, most of them work in a similar manner.</p>
<div class="highlight-python"><pre>ourString=’python is the best language ever’


# Capitalize a String
&gt;&gt;&gt; ourString.capitalize()
'Python is the best language ever'

# Center string
&gt;&gt;&gt; ourString.center(50)
'         python is the best language ever         '
&gt;&gt;&gt; ourString.center(50,'-')
'---------python is the best language ever---------'

# Count substring within a string
&gt;&gt;&gt; ourString.count('a')
2

# Partition a string
&gt;&gt;&gt; x = "Hello, my name is Josh"
&gt;&gt;&gt; x.partition('n')
('Hello, my ', 'n', 'ame is Josh')</pre>
</div>
<div class="section" id="string-formatting">
<h4>String Formatting<a class="headerlink" href="#string-formatting" title="Permalink to this headline"></a></h4>
<p>You have many options when printing strings using the <em>print</em> statement.  Much like the C programming language, Python string
formatting allows you to make use of a number of different conversion types when printing.</p>
<div class="highlight-python"><pre>Using String Formatting
# The two syntaxes below work the same
&gt;&gt;&gt; x = "Josh"
&gt;&gt;&gt; print "My name is %s" % (x)
My name is Josh
&gt;&gt;&gt; print "My name is %s" % x
My name is Josh</pre>
</div>
<table border="1" class="docutils">
<colgroup>
<col width="7%" />
<col width="93%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Type</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>d</td>
<td>signed integer decimal</td>
</tr>
<tr><td>i</td>
<td>signed integer decimal</td>
</tr>
<tr><td>o</td>
<td>unsigned octal</td>
</tr>
<tr><td>u</td>
<td>unsigned decimal</td>
</tr>
<tr><td>x</td>
<td>unsigned hexidecimal</td>
</tr>
<tr><td>X</td>
<td>unsigned hexidecimal (upper)</td>
</tr>
<tr><td>E</td>
<td>floating point exponential format (upper)</td>
</tr>
<tr><td>e</td>
<td>floating point exponential format</td>
</tr>
<tr><td>f</td>
<td>floating point decimal format</td>
</tr>
<tr><td>F</td>
<td>floating point decimal format (upper)</td>
</tr>
<tr><td>g</td>
<td>floating point exponential format if exponent &gt; -4, otherwise float</td>
</tr>
<tr><td>G</td>
<td>floating point exponential format (uppr) if exponent &gt; -4, otherwise float</td>
</tr>
<tr><td>c</td>
<td>single character</td>
</tr>
<tr><td>r</td>
<td>string (converts any python object using repr())</td>
</tr>
<tr><td>s</td>
<td>string (converts any python object using str())</td>
</tr>
<tr><td>%</td>
<td>no conversion, results in a percent (%) character</td>
</tr>
</tbody>
</table>
<p>Table 2-3.  Conversion Types</p>
<blockquote>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mf">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="mf">5.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="s">&#39;The expression </span><span class="si">%d</span><span class="s"> * </span><span class="si">%f</span><span class="s"> results in </span><span class="si">%f</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="p">)</span>
<span class="go">The expression 10 * 5.750000 results in 57.500000</span>
</pre></div>
</div>
</blockquote>
</div>
</div>
<div class="section" id="ranges">
<h3>Ranges<a class="headerlink" href="#ranges" title="Permalink to this headline"></a></h3>
<p>Ranges are not really a data type or a container; they are really a Jython built-in function (Chapter 4).  For this reason,
we will only briefly touch upon the range function here, and they’ll be covered in more detail in Chapter 4.  However,
because they play such an important role in the iteration of data, usually via the <em>for</em> loop, I think it is important to
discuss them in this section of the book.  The range is a special function that allows one to iterate between a range of
numbers; and/or list a specific range of numbers.  It is especially helpful for performing mathematical iterations, but
it can also be used for simple iterations.</p>
<p>The format for using the range function includes an optional starting number, an ending number, and an optional stepping number.
If specified, the starting number tells the range where to begin, whereas the ending number specifies where the range should end.
The optional step number tells the range how many numbers should be placed between each number contained within the range output.</p>
<div class="section" id="range-format">
<h4>Range Format<a class="headerlink" href="#range-format" title="Permalink to this headline"></a></h4>
<blockquote>
range([start], stop, [step])</blockquote>
<div class="highlight-python"><div class="highlight"><pre><span class="go">&gt;&gt;&gt;range(0,10)</span>

<span class="go">&gt;&gt;&gt;range(10)</span>

<span class="go">&gt;&gt;&gt;range(0,10,2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mf">100</span><span class="p">,</span><span class="mf">0</span><span class="p">,</span><span class="o">-</span><span class="mf">10</span><span class="p">)</span>
<span class="go">[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]</span>
</pre></div>
</div>
<p>As stated previously, this function can be quite useful when used within a <em>for</em> loop as the Jython <em>for</em> loop syntax works
very well with it.  The following example displays a couple examples of using the range function within a <em>for</em> loop context.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mf">10</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">0</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">4</span>
<span class="go">5</span>
<span class="go">6</span>
<span class="go">7</span>
<span class="go">8</span>
<span class="go">9</span>

<span class="go"># Multiplication Example</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mf">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mf">2</span><span class="p">,</span> <span class="mf">10</span><span class="p">,</span> <span class="mf">2</span><span class="p">):</span>
<span class="gp">... </span>        <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="p">(</span><span class="n">i</span> <span class="o">*</span> <span class="n">x</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="go">3</span>
<span class="go">15</span>
<span class="go">105</span>
<span class="go">945</span>
</pre></div>
</div>
<p>As you can see, a range can be used to iterate through just about any number set...be it positive or negative in range.</p>
</div>
</div>
<div class="section" id="lists-dictionaries-sets-and-tuples">
<h3>Lists, Dictionaries, Sets, and Tuples<a class="headerlink" href="#lists-dictionaries-sets-and-tuples" title="Permalink to this headline"></a></h3>
<p>Data collection containers are a useful tool for holding and passing data throughout the lifetime of an application.  The data
can come from any number of places, be it the keyboard, a file on the system, or a database…it can be stored in a collection
container and used at a later time.  Lists, dictionaries, sets, and tuples all offer similar functionality and usability, but
they each have their own niche in the language.  We’ll go through several examples of each since they all play an important role
under certain circumstances.</p>
<p>Since these containers are so important, we’ll go through an exercise at the end of this chapter, which will give you a chance
to try them out for yourself.</p>
<div class="section" id="lists">
<h4>Lists<a class="headerlink" href="#lists" title="Permalink to this headline"></a></h4>
<p>Perhaps one of the most used constructs within the Python programming language is the list.  Most other programming languages
provide similar containers for storing and manipulating data within an application.  The Python list provides an advantage to
those similar constructs which are available in statically typed languages.  The dynamic tendencies of the Python language help
the list construct to harness the great feature of having the ability to contain values of different types.  This means that a
list can be used to store any Python data type, and these types can be mixed within a single list.  In other languages, this type
of construct is defined as a typed object, which locks the construct to using only one data type.</p>
<p>The creation and usage of Jython lists is just the same as the rest of the language…very simple and easy to use.  Simply assigning
a set of empty square brackets to a variable creates an empty list.  We can also use the built-in list() type to create a list.
The list can be constructed and modified as the application runs, they are not declared with a static length.  They are easy to
traverse through the usage of loops, and indexes can also be used for positional placement or removal of particular items in the list.
We’ll start out by showing some examples of defining lists, and then go through each of the different avenues which the Jython
language provides us for working with lists.</p>
<div class="highlight-python"><pre># Define an empty list
myList = []
myList = list()

# Define a list of string values
myStringList = [‘Hello’,’Jython’,’Lists’]

# Define a list containing mulitple data types
multiList = [1,2,’three’,4,’five’,’six’]

# Define a list containing a list
comboList = [1,myStringList,multiList]</pre>
</div>
<p>As stated previously, in order to obtain the values from a list we can make use of indexes.  Much like the Array in the Java language,
using the <em>list[index]</em> notation will allow us to access an item.  If we wish to obtain a range or set of values from a list, we can
provide a <em>starting</em> index, and/or an <em>ending</em> index.  This technique is also known as <em>slicing</em>.  What’s more, we can also return
a set of values from the list along with a stepping pattern by providing a <em>step</em> index as well.  One key to remember is that while
accessing a list via indexing, the first element in the list is contained within the 0 index.</p>
<div class="highlight-python"><pre># Obtain elements in the list
&gt;&gt;&gt; myStringList[0]
‘Hello’

&gt;&gt;&gt; myStringList[2]
‘Lists’

&gt;&gt;&gt; myStringList[-1]
'Lists'

# Using the slice method
&gt;&gt;&gt; myStringList[0:2]
['Hello', 'Jython']

# Return every other element in a list
&gt;&gt;&gt; newList=[2,4,6,8,10,12,14,16,18,20]
&gt;&gt;&gt; newList[0:10:2]
[2, 6, 10, 14, 18]

# Leaving a positional index blank will also work
&gt;&gt;&gt; newList[::2]
[2, 6, 10, 14, 18]</pre>
</div>
<p>Modifying a list is much the same, you can either use the index in order to insert or remove items from a particular position.
There are also many other ways that you can insert or remove elements from the list.  Jython provides each of these different
options as they provide different functionality for your operations.</p>
<p>In order to add an item to a list, you can make use of the <em>append()</em> method in order to add an item to the end of a list.
The <em>extend()</em> method allows you to add an entire list or sequence to the end of a list.  Lastly, the <em>insert()</em> method
allows you to place an item or list into a particular area of an existing list by utilizing positional indexes.
You will examples of each method below.</p>
<p>Similarly, we have plenty of options for removing items from a list.  The <em>del</em> statement, as explained in Chapter 1,
can be used to remove or delete an entire list or values from a list using the index notation.  You can also use the
<em>pop() *or *remove()</em> method to remove single values from a list.  The <em>pop()</em> method will remove a single value from
the end of the list, and it will also return that value at the same time.  If an index is provided to the <em>pop()</em> function,
then it will remove and return the value at that index.  The <em>remove()</em> method can be used to find and remove a particular
value in the list.  If more than one value in the list matches the value passed into the <em>remove()</em> function, the first one
will be removed.  Another note about the <em>remove()</em> function is that the value removed is not returned.  Let’s take a look
at these examples of modifying a list.</p>
<div class="highlight-python"><pre># Adding values to a list
&gt;&gt;&gt; newList=['a','b','c','d','e','f','g']
&gt;&gt;&gt; newList.append('h')
&gt;&gt;&gt; print newList
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

# Add another list to the existing list
&gt;&gt;&gt; newList2=['h','i','j','k','l','m','n','o','p']
&gt;&gt;&gt; newList.extend(newList2)
&gt;&gt;&gt; print newList
['a', 'b', 'c', 'd', 'e', 'f', 'g', ‘h’,'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']

# Insert a value into a particular location via the index
&gt;&gt;&gt; newList.insert(2,'c')
&gt;&gt;&gt; print newList
['a', 'b', 'c', 'c', 'd', 'e', 'f', 'g', 'h', ‘h’,'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']

# Use the slice notation to insert another list or sequence
&gt;&gt;&gt; newListA=[100,200,300,400]
&gt;&gt;&gt; newListB=[500,600,700,800]
&gt;&gt;&gt; newListA[0:2]=newListB
&gt;&gt;&gt; print newListA
[500, 600, 700, 800, 300, 400]

# Use the del statement to delete a list
&gt;&gt;&gt; newList3=[1,2,3,4,5]
&gt;&gt;&gt; print newList3
[1, 2, 3, 4, 5]
&gt;&gt;&gt; del newList3
&gt;&gt;&gt; print newList3
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'newList3' is not defined

# Use the del statement to remove a value or range of values from a list
&gt;&gt;&gt; newList3=['a','b','c','d','e','f']
&gt;&gt;&gt; del newList3[2]
&gt;&gt;&gt; newList3
['a', 'b', 'd', 'e', 'f']
&gt;&gt;&gt; del newList3[1:3]
&gt;&gt;&gt; newList3
['a', 'e', 'f']

# Remove values from a list using pop and remove functions
&gt;&gt;&gt; print newList
['a', 'b', 'c', 'c', 'd', 'e', 'f', 'g', 'h',’h’, 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
&gt;&gt;&gt; newList.pop(2)
'c'
&gt;&gt;&gt; print newList
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',’h’, 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
&gt;&gt;&gt; newList.remove('h')
&gt;&gt;&gt; print newList
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']

# Useful example of using pop() function
&gt;&gt;&gt; x = 5
&gt;&gt;&gt; timesList = [1,2,3,4,5]
&gt;&gt;&gt; while timesList:
...     print x * timesList.pop(0)
...
5
10
15
20
25</pre>
</div>
<p>Now that we know how to add and remove items from a list, it is time to learn how to manipulate the data within them.
Python provides a number of different methods that can be used to help us manage our lists.  See the table below for a
list of these functions and what they can do.</p>
<table border="1" class="docutils">
<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Method</th>
<th class="head">Tasks Performed</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>index</td>
<td>Returns the index of the first value in the list which matches a given value.</td>
</tr>
<tr><td>count</td>
<td>Returns the number of items in the list which match a given value.</td>
</tr>
<tr><td>sort</td>
<td>Sorts the items contained within the list.</td>
</tr>
<tr><td>reverse</td>
<td>Reverses the order of the items contained within the list</td>
</tr>
</tbody>
</table>
<p>Table 2-4.  Python List Methods</p>
<p>Let’s take a look at some examples of how these functions can be used on lists.</p>
<div class="highlight-python"><pre># Returning the index for any given value
&gt;&gt;&gt; newList=[1,2,3,4,5,6,7,8,9,10]
&gt;&gt;&gt; newList.index(4)
3

# Add a duplicate into the list and then return the index
&gt;&gt;&gt; newList.append(6)
&gt;&gt;&gt; newList
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6]
&gt;&gt;&gt; newList.index(6)
5

# Using count() function to return the number of items which match a given value
&gt;&gt;&gt; newList.count(2)
1
&gt;&gt;&gt; newList.count(6)
2

# Sort the values in the list
&gt;&gt;&gt; newList.sort()
&gt;&gt;&gt; newList
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]

# Reverse the order of the value in the list
&gt;&gt;&gt; newList.reverse()
&gt;&gt;&gt; newList
[10, 9, 8, 7, 6, 6, 5, 4, 3, 2, 1]</pre>
</div>
</div>
<div class="section" id="id1">
<h4>Lists<a class="headerlink" href="#id1" title="Permalink to this headline"></a></h4>
<p>Moving around within a list is quite simple.  Once a list is populated, often times we wish to traverse through it
and perform some action against each element contained within it.  You can use any of the Python looping constructs
to traverse through each element within a list.  While there are plenty of options available, the <em>for</em> loop works
especially well.  The reason is because of the simple syntax that the Python <em>for</em> loop uses.  This section will show
you how to traverse a list using each of the different Python looping constructs.  You will see that each of them has
advantages and disadvantages.</p>
<p>Let’s first take a look at the syntax that is used to traverse a list using a <em>for</em> loop.  This is by far one of the
easiest modes of going through each of the values contained within a list.  The <em>for</em> loop traverses the list one
element at a time, allowing the developer to perform some action on each element if so desired.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">ourList</span><span class="o">=</span><span class="p">[</span><span class="mf">1</span><span class="p">,</span><span class="mf">2</span><span class="p">,</span><span class="mf">3</span><span class="p">,</span><span class="mf">4</span><span class="p">,</span><span class="mf">5</span><span class="p">,</span><span class="mf">6</span><span class="p">,</span><span class="mf">7</span><span class="p">,</span><span class="mf">8</span><span class="p">,</span><span class="mf">9</span><span class="p">,</span><span class="mf">10</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">ourList</span><span class="p">:</span>
<span class="gp">... </span>   <span class="k">print</span> <span class="n">elem</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">4</span>
<span class="go">5</span>
<span class="go">6</span>
<span class="go">7</span>
<span class="go">8</span>
<span class="go">9</span>
<span class="go">10</span>
</pre></div>
</div>
<p>As you can see from this simple example, it is quite easy to go through a list and work with each item individually.  The
<em>for</em> loop syntax requires a variable to which each element in the list will be assigned for each pass of the loop.
Additionally, we can still make use of the current index while traversing a loop this way if needed.  The only requirement
is to make use of the <em>index()</em> method on the list and pass the current element.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="go">&gt;&gt;&gt;ourList=[1,2,3,4,5,6,7,8,9,10]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">ourList</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&#39;The current index is: </span><span class="si">%d</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">ourList</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">elem</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">The current index is: 0</span>
<span class="go">The current index is: 1</span>
<span class="go">The current index is: 2</span>
<span class="go">The current index is: 3</span>
<span class="go">The current index is: 4</span>
<span class="go">The current index is: 5</span>
<span class="go">The current index is: 6</span>
<span class="go">The current index is: 7</span>
<span class="go">The current index is: 8</span>
<span class="go">The current index is: 9</span>
</pre></div>
</div>
<p>If we do not wish to go through each element within the list then that is also possible via the use of the <em>for</em> loop.
In this case, we’ll simply use a list slice to retrieve the exact elements we want to see.  For instance, take a look
a the following code which traverses through the first 5 elements in our list.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">ourList</span><span class="p">[</span><span class="mf">0</span><span class="p">:</span><span class="mf">5</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">elem</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">4</span>
<span class="go">5</span>
</pre></div>
</div>
<p>To illustrate a more detailed example, lets say that you wished to retrieve every other element within the list.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">ourList</span><span class="p">[</span><span class="mf">0</span><span class="p">::</span><span class="mf">2</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">elem</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">3</span>
<span class="go">5</span>
<span class="go">7</span>
<span class="go">9</span>
</pre></div>
</div>
<p>As you can see, doing so is quite easy by simply making use of the built-in features that Python offers.</p>
</div>
<div class="section" id="list-comprehensions">
<h4>List Comprehensions<a class="headerlink" href="#list-comprehensions" title="Permalink to this headline"></a></h4>
<p>There are some advanced features for lists that can help to make a developer’s life easier.  Once such feature is known
as a <em>list comprehension</em>.  While this concept may be daunting at first, it offers a good alternative to creating many separate
lists manually or using map().  List comprehensions take a given list, and then iterate through it and apply a given expression
against each of the objects in the list.  This allows one to quickly take a list and alter it via the use of the provided expression.
Of course, as with many other Python methods the list comprehension returns an altered copy of the list.  The original list is left untouched.</p>
<p>Let’s take a look at the syntax for a list comprehension.  They are basically comprised of an expression of some kind followed by a
<em>for</em> statement and then optionally more <em>for</em> or <em>if</em> statements.  As they are a difficult technique to describe, let’s take a look
at some examples.  Once you’ve seen list comprehensions in action you are sure to understand them and see how useful they can be.</p>
<div class="highlight-python"><pre># Create a list of ages and add one to each of those ages using a list comprehension
&gt;&gt;&gt; ages=[20,25,28,30]
&gt;&gt;&gt; [age+1 for age in ages]
[21, 26, 29, 31]

# Create a list of names and convert the first letter of each name to uppercase as it should be
&gt;&gt;&gt; names=['jim','frank','vic','leo','josh']
&gt;&gt;&gt; [name.title() for name in names]
['Jim', 'Frank', 'Vic', 'Leo', 'Josh']

# Create a list of numbers and return the square of each EVEN number
&gt;&gt;&gt; numList=[1,2,3,4,5,6,7,8,9,10,11,12]
&gt;&gt;&gt; [num*num for num in numList if num % 2 == 0]
[4, 16, 36, 64, 100, 144]

# Use a list comprehension with a range
&gt;&gt;&gt; [x*5 for x in range(1,20)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]</pre>
</div>
<p>List comprehensions can make code much more concise and allows one to apply expressions or functions to list elements quite easily.
Let’s take a quick look at an example written in Java for performing the same type of work as an easy list comprehension.  It is plain
to see that list comprehensions are much more concise.</p>
<div class="highlight-python"><pre>int[] ages = {20, 25, 28, 30};

// Use a newstyle Java for loop to go through each element in the array
for (int age : ages){
    age++;
}</pre>
</div>
</div>
<div class="section" id="dictionaries">
<h4>Dictionaries<a class="headerlink" href="#dictionaries" title="Permalink to this headline"></a></h4>
<p>A dictionary is quite different than a typical list in Python as there is no automatically populated index for any given element
within the dictionary.  When you use a list, you need not worry about assigning an index to any value that is placed within it.
However, a dictionary forces the developer to assign an index or “key” for every element that is placed into the construct.  Therefore,
each entry into a dictionary requires two values, the <em>key</em> and the <em>element</em>.</p>
<p>The beauty of the dictionary is that it allows the developer to choose the data type of the key value.  Therefore, if one wishes
to use a string value as a key then it is entirely possible.  Dictionary types also have a multitude of methods and operations that
can be applied to them to make them easier to work with.</p>
<table border="1" class="docutils">
<colgroup>
<col width="55%" />
<col width="45%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Method or Operation</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>len(dictionary)</td>
<td>Returns number of items within the given dictionary.</td>
</tr>
<tr><td>dictionary[key]</td>
<td>Returns the item from the list that is associated with the given key.</td>
</tr>
<tr><td>dictionary[key] = value</td>
<td>Sets the associated item in the list to the given value.</td>
</tr>
<tr><td>del dictionary[key]</td>
<td>Deletes the given key/value pair from the list.</td>
</tr>
<tr><td>dictionary.clear()</td>
<td>Removes all items from the dictionary.</td>
</tr>
<tr><td>dictionary.copy()</td>
<td>Creates a shallow copy of the dictionary.</td>
</tr>
<tr><td>has_key(key)</td>
<td>Returns a boolean stating whether the dictionary contains the given key.</td>
</tr>
<tr><td>items()</td>
<td>Returns a copy of the key/value pairs within the dictionary.</td>
</tr>
<tr><td>keys()</td>
<td>Returns the keys within the dictionary.</td>
</tr>
<tr><td>update([dictionary2])</td>
<td>Updates dictionary with the key/value pairs from the given dictionary.  Existing keys will be overwritten.</td>
</tr>
<tr><td>fromkeys(sequence[,value])</td>
<td>Creates a new dictionary with keys from the given sequence.  The values will be set to the values given.</td>
</tr>
<tr><td>values()</td>
<td>Returns the values within the dictionary.</td>
</tr>
<tr><td>get(key[, b])</td>
<td>Returns the value associated with the given key.  If the key does not exist, then returns b.</td>
</tr>
<tr><td>setdefault(key[, b])</td>
<td>Returns the value associated with the given key.  If the key does not exist, then returns and sets b.</td>
</tr>
<tr><td>pop(key[, b])</td>
<td>Returns and removes the value associated with the given key.  If the key does not exist then returns b.</td>
</tr>
<tr><td>popItem()</td>
<td>Removes and returns the first key/value pair in the dictionary.</td>
</tr>
<tr><td>iteritems()</td>
<td>Returns an iterator over the key/value pairs in the dictionary.</td>
</tr>
<tr><td>iterkeys()</td>
<td>Returns an iterator over the keys in the dictionary.</td>
</tr>
<tr><td>itervalues()</td>
<td>Returns an iterator over the values in the dictionary.</td>
</tr>
</tbody>
</table>
<p>Table 2-5.  Mapping type methods and operations.</p>
<p>Now we will take a look at some dictionary examples.  This reference will not show you an example of using each of the mapping operations,
but it should provide you with a good enough base understanding of how they work.</p>
<div class="highlight-python"><pre># Create an empty dictionary and a populated dictionary
&gt;&gt;&gt; myDict={}
&gt;&gt;&gt; myDict.values()
[]
&gt;&gt;&gt; myDict.has_key(1)
False
&gt;&gt;&gt; myDict[1] = 'test'
&gt;&gt;&gt; myDict.values()
['test']
&gt;&gt;&gt; len(myDict)
1

# Replace the original dictionary with a dictionary containing string-based keys
# The following dictionary represents a hockey team line
&gt;&gt;&gt; myDict = {'r_wing':'Josh','l_wing':'Frank','center':'Jim','l_defense':'Leo','r_defense':'Vic'}
&gt;&gt;&gt; myDict.values()
['Josh', 'Vic', 'Jim', 'Frank', 'Leo']
&gt;&gt;&gt; myDict.get('r_wing')
'Josh'

# Iterate over the items in the dictionary
&gt;&gt;&gt; hockeyTeam = myDict.iteritems()
&gt;&gt;&gt; for player in hockeyTeam:
...     print player
...
('r_wing', 'Josh')
('r_defense', 'Vic')
('center', 'Jim')
('l_wing', 'Frank')
('l_defense', 'Leo')

&gt;&gt;&gt; for key,value in myDict.iteritems():
...     print key, value
...
r_wing Josh
r_defense Vic
center Jim
l_wing Frank
l_defense Leo</pre>
</div>
</div>
<div class="section" id="sets">
<h4>Sets<a class="headerlink" href="#sets" title="Permalink to this headline"></a></h4>
<p>Sets are unordered collections of unique elements.  What makes sets different than other sequence types is that they contain
no indexing.  They are also unlike dictionaries because there are no key values associated with the elements.  They are an arbitrary
collection of unique elements.  Sets cannot contain mutable objects, but they can be mutable.</p>
<p>There are two different types of sets, namely <em>set</em> and <em>frozenset</em>.  The difference between the two is quite easily conveyed
from the name itself.  A regular <em>set</em> is a mutable collection object, whereas a <em>frozen</em> set is immutable.  Much like sequences and
mapping types, sets have an assortment of methods and operations that can be used on them.  Many of the operations and methods work
on both mutable and immutable sets.  However, there are a number of them that only work on the mutable set types.  In the two tables
that follow, we’ll take a look at the different methods and operations.</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Method or Operation</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>len(set)</td>
<td>Returns the number of elements in a given set.</td>
</tr>
<tr><td>copy()</td>
<td>&nbsp;</td>
</tr>
<tr><td>difference(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>intersection(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>issubbset(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>issuperset(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>symmetric_difference(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>union(set2)</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Table 2-6.  Set Type Methods and Operations</p>
<table border="1" class="docutils">
<colgroup>
<col width="34%" />
<col width="66%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Method or Operation</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>add(item)</td>
<td>Adds an item to a set if it is not already in the set.</td>
</tr>
<tr><td>clear()</td>
<td>Removes all items in a set.</td>
</tr>
<tr><td>difference_update(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>discard(item)</td>
<td>&nbsp;</td>
</tr>
<tr><td>intersection_update(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>pop()</td>
<td>&nbsp;</td>
</tr>
<tr><td>remove()</td>
<td>&nbsp;</td>
</tr>
<tr><td>symmetric_difference_update(set2)</td>
<td>&nbsp;</td>
</tr>
<tr><td>update(set2)</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Table 2-7.  Mutable Set Type Methods and Operations</p>
</div>
<div class="section" id="tuples">
<h4>Tuples<a class="headerlink" href="#tuples" title="Permalink to this headline"></a></h4>
<p>Tuples are much like lists, however they are immutable.  Once a tuple has been defined, it cannot be changed.
They contain indexes just like lists, but again, they cannot be altered once defined.  Therefore, the index in
a tuple may be used to retrieve a particular value and not to assign or modify.</p>
<p>Since tuples are a member of the sequence type, they can use the same set of methods an operations available
to all sequence types.</p>
<div class="highlight-python"><pre># Creating an empty tuple
&gt;&gt;&gt; myTuple = ()

# Creating tuples and using them
&gt;&gt;&gt; myTuple2 = (1, 'two',3, 'four')
&gt;&gt;&gt; myTuple2
(1, 'two', 3, 'four')</pre>
</div>
</div>
</div>
<div class="section" id="jython-specific-collections">
<h3>Jython Specific Collections<a class="headerlink" href="#jython-specific-collections" title="Permalink to this headline"></a></h3>
<p>There are a number of Jython specific collection objects that are available for use.  Most of these collection
objects are used to pass data into Java classes and so forth, but they add additional functionality into the Jython
implementation that will assist Python newcomers that are coming from the Java world.  Nonetheless, many of these
additional collection objects can be quite useful under certain situations.</p>
<p>In the Jython 2.2 release, Java collection integration was introduced.  This enables a bidirectional interaction
between Jython and Java collection types.  For instance, a Java ArrayList can be imported in Jython and then used
as if it were part of the language.  Prior to 2.2, Java collection objects could act as a Jython object, but Jython
objects could not act as Java objects.</p>
<div class="highlight-python"><pre># Import and use a Java ArrayList
&gt;&gt;&gt; import java.util.ArrayList as ArrayList
&gt;&gt;&gt; arr = ArrayList()
&gt;&gt;&gt; arr.add(1)
True
&gt;&gt;&gt; arr.add(2)
True
&gt;&gt;&gt; print arr
[1, 2]</pre>
</div>
<p>Ahead of the integration of Java collections, Jython also had implemented the <em>jarray</em> object which basically allows
for the construction of a Java array in Jython.  In order to work with a <em>jarray</em>, simply define a sequence type in
Jython and pass it to the <em>jarray</em> object along with the type of object contained within the sequence.  The <em>jarray</em>
is definitely useful for creating Java arrays and then passing them into java objects, but it is not very useful for
working in Jython objects.  Moreover, all values within a jarray must be the same type.  If you try to pass a sequence
containing multiple types to a jarray then you’ll be given a <em>TypeError</em> of one kind or another.</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="8%" />
<col width="43%" />
<col width="23%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Character</th>
<th class="head">&nbsp;</th>
<th class="head">Java Equivalent</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>z</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>boolean</td>
</tr>
<tr><td>b</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>byte</td>
</tr>
<tr><td>c</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>char</td>
</tr>
<tr><td>d</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>double</td>
</tr>
<tr><td>f</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>float</td>
</tr>
<tr><td>h</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>short</td>
</tr>
<tr><td>i</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>int</td>
</tr>
<tr><td>l</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>long</td>
</tr>
</tbody>
</table>
<p>Table 2-8. Character Typecodes for use with Jarray</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">mySeq</span> <span class="o">=</span> <span class="p">(</span><span class="mf">1</span><span class="p">,</span><span class="mf">2</span><span class="p">,</span><span class="mf">3</span><span class="p">,</span><span class="mf">4</span><span class="p">,</span><span class="mf">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">jarray</span> <span class="kn">import</span> <span class="n">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">array</span><span class="p">(</span><span class="n">mySeq</span><span class="p">,</span><span class="nb">int</span><span class="p">)</span>
<span class="go">array(org.python.core.PyInteger, [1, 2, 3, 4, 5])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">myStr</span> <span class="o">=</span> <span class="s">&quot;Hello Jython&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">array</span><span class="p">(</span><span class="n">myStr</span><span class="p">,</span><span class="s">&#39;c&#39;</span><span class="p">)</span>
<span class="go">array(&#39;c&#39;, &#39;Hello Jython&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="files">
<h3>Files<a class="headerlink" href="#files" title="Permalink to this headline"></a></h3>
<p>File objects are used to read and write data to a file on disk.  The file object is used to obtain a reference
to the file on disk and open it for reading, writing, appending, or a number of different tasks.  If we simply
use the <em>open(filename[, mode])</em> function, we can return a file type and assign it to a variable for processing.
If the file does not yet exist on disk, then it will automatically be created.  The <em>mode</em> argument is used to
tell what type of processing we wish to perform on the file.  This argument is optional and if omitted then the
file is opened in read-only mode.</p>
<table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="7%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Mode</th>
<th class="head">&nbsp;</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>‘r’</td>
<td>&nbsp;</td>
<td>read only</td>
</tr>
<tr><td>‘w’</td>
<td>&nbsp;</td>
<td>write</td>
</tr>
<tr><td>‘a’</td>
<td>&nbsp;</td>
<td>append</td>
</tr>
<tr><td>‘r+’</td>
<td>&nbsp;</td>
<td>read and write</td>
</tr>
<tr><td>‘rb’</td>
<td>&nbsp;</td>
<td>Windows binary file read</td>
</tr>
<tr><td>‘wb’</td>
<td>&nbsp;</td>
<td>Windows binary file write</td>
</tr>
<tr><td>‘r+b’</td>
<td>&nbsp;</td>
<td>Windows binary file read and write</td>
</tr>
</tbody>
</table>
<p>Table 2-9.  Modes of Operations for File Types</p>
<blockquote>
# Open a file and assign it to variable f</blockquote>
<p>There are plenty of methods that can be used on file objects for manipulation of the file content.  We can call
<em>read([size])</em> on a file in order to read it’s content.  Size is an optional argument here and it is used to tell
how much content to read from the file.  If it is omitted then the entire file content is read.  The <em>readline()</em>
method can be used to read a single line from a file.  <em>readlines([size])</em> is used to return a list containing
all of the lines of data that are contained within a file.  Again, there is an optional <em>size</em> parameter that
can be used to tell how many bytes from the file to read.  If we wish to place content into the file, the <em>write(string)</em>
method does just that.  The <em>write()</em> method writes a string to the file.</p>
<p>When writing to a file it is oftentimes important to know exactly what position in the file you are going to write to.
There are a group of methods to help us out with positioning within a file using integers to represent bytes in the file.
The <em>tell()</em> method can be called on a file to give the file object’s current position.  The integer returned is in bytes
and is an offset from the beginning of the file.  The <em>seek(offset, from)</em> method can be used to change position in a
file.  The <em>offset</em> is the number in bytes of the position you’d like to go, and <em>from</em> represents the place in the file
where you’d like to calculate the <em>offset</em> from.  If <em>from</em> equals 0, then the offset will be calculated from the beginning
of the file.  Likewise, if it equals 1 then it is calculated from the current file position, and 2 will be from the end of
the file.  The default is 0 if <em>from</em> is omitted.</p>
<p>Lastly, it is important to allocate and de-allocate resources efficiently in our programs or we will incur a memory overhead
and leaks.  The <em>close()</em> method should be called on a file when we are through working with it.  The proper methodology
to use when working with a file is to open, process, and then close each time.  However, there are more efficient ways
of performing such tasks.  In Chapter 5 we will discuss the use of context managers to perform the same functionality in
a more efficient manner.</p>
<div class="highlight-python"><pre>File Manipulation in Python
# Create a file, write to it, and then read it’s content

&gt;&gt;&gt; f = open('newfile.txt','r+')
&gt;&gt;&gt; f.write('This is some new text for our file\n')
&gt;&gt;&gt; f.write('This should be another line in our file\n')
#  No lines will be read because we are at the end of the written content
&gt;&gt;&gt; f.read()
''
&gt;&gt;&gt; f.readlines()
[]
&gt;&gt;&gt; f.tell()
75L
# Move our position back to the beginning of the file
&gt;&gt;&gt; f.seek(0)
&gt;&gt;&gt; f.read()
'This is some new text for our file\nThis should be another line in our file\n'
&gt;&gt;&gt; f.seek(0)
&gt;&gt;&gt; f.readlines()
['This is some new text for our file\n', 'This should be another line in our file\n']
&gt;&gt;&gt; f.close()</pre>
</div>
</div>
<div class="section" id="iterators">
<h3>Iterators<a class="headerlink" href="#iterators" title="Permalink to this headline"></a></h3>
<p>The iterator type was introduced into Python back in version 2.2.  It allows for iteration over Python containers.
All iterable containers have built-in support for the iterator type.  For instance, sequence objects are iterable
as they allow for iteration over each element within the sequence.  If you try to return an iterator on an object
that does not support iteration, you will most likely receive an <em>AttributeError</em> which tells you that __iter__
has not been defined as an attribute for that object.</p>
<p>Iterators allow for easy access to sequences and other iterable containers.  Some containers such as dictionaries
have specialized iteration methods built into them as you have seen in previous sections.  Iterator objects are
required to support two main methods that form the iterator protocol.  Those methods are defined below.</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="61%" />
<col width="25%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Method</th>
<th class="head">Description</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>iterator.__iter__()</td>
<td>Returns the iterator object on a container.  Required to allow use with <em>for</em> and <em>in</em> statements</td>
<td>&nbsp;</td>
</tr>
<tr><td>iterator.next()</td>
<td>Returns the next item from a container.</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Table 2-10:  Iterator Protocol</p>
<p>To return an iterator on a container, just assign <em>container.__iter__()</em> to some variable.  That variable will become
the iterator for the object.  If using the <em>next()</em> call, it will continue to return the next item within the list
until all items have been retrieved.  Once this occurs, a <em>StopIteration</em> error is issued.  The important thing to note
here is that we are actually creating a copy of the list when we return the iterator and assign it to a variable.  That
variable returns and removes an item from that copy each time the <em>next()</em> method is called on it.  If we continue to
call <em>next()</em> on the iterator variable until the <em>StopIteration</em> error is issued, the variable will no longer contain
any items and is empty.</p>
</div>
</div>
<div class="section" id="referencing-and-copies">
<h2>Referencing and Copies<a class="headerlink" href="#referencing-and-copies" title="Permalink to this headline"></a></h2>
<p>Creating copies and referencing items in the Python language is fairly straightforward.  The only thing you’ll need to
keep in mind is that the techniques used to copy mutable and immutable objects differ a bit.</p>
<p>In order to create a copy of an immutable object, you simply assign it to a different variable.  The new variable is an
exact copy of the object.  If you attempt to do the same with a mutable object, you will actually just create a reference
to the original object.  Therefore, if you perform operations on the “copy” of the original then the same operation will
actually be performed on the original.  This occurs because the new assignment references the same mutable object in memory
as the original.  It is kind of like someone calling you by a different name.  One person may call you by your birth name
and another may call you by your nickname, but both names will reference you of course.</p>
<p>To effectively create a copy of a mutable object, you have two choices.  You can either create what is known as a <em>shallow</em>
copy or a <em>deep</em> copy of the original object.  The difference is that a shallow copy of an object will create a new object
and then populate it with references to the items that are contained in the original object.  Hence, if you modify any of
those items then each object will be affected since they both reference the same items.  A deep copy creates a new object
and then recursively copies the contents of the original object into the new copy.  Once you perform a deep copy of an object
then you can perform operations on the copied object without affecting the original.  You can use the <em>deepcopy</em> function in
the Python standard library to create such a copy.  Let’s look at some examples of creating copies in order to give you a
better idea of how this works.</p>
<div class="highlight-python"><pre># Create an integer variable, copy it, and modify the copy
&gt;&gt;&gt; a = 5
&gt;&gt;&gt; b = a
&gt;&gt;&gt; print b
5
&gt;&gt;&gt; b = a * 5
&gt;&gt;&gt; b
25
&gt;&gt;&gt; a
5

# Create a list, assign it to a different variable and then modify
&gt;&gt;&gt; listA = [1,2,3,4,5,6]
&gt;&gt;&gt; print listA
[1, 2, 3, 4, 5, 6]
&gt;&gt;&gt; listB = listA
&gt;&gt;&gt; print listB
[1, 2, 3, 4, 5, 6]
&gt;&gt;&gt; del listB[2]
# Oops, we’ve altered the original list!
&gt;&gt;&gt; print listA
[1, 2, 4, 5, 6]

# Create a deep copy of the list and modify it
&gt;&gt;&gt; import copy
&gt;&gt;&gt; listA = [1,2,3,4,5,6]
&gt;&gt;&gt; listB = copy.deepcopy(listA)
&gt;&gt;&gt; print listA
[1, 2, 3, 4, 5, 6]
&gt;&gt;&gt; del listB[2]
&gt;&gt;&gt; print listB
[1, 2, 4, 5, 6]
&gt;&gt;&gt; print listA
[1, 2, 3, 4, 5, 6]</pre>
</div>
</div>
<div class="section" id="garbage-collection">
<h2>Garbage Collection<a class="headerlink" href="#garbage-collection" title="Permalink to this headline"></a></h2>
<p>This is one of those major differences between CPython and Jython.  Unline CPython, Jython does not implement a
reference counting technique for aging out or garbage collection unused objects.  Instead, Jython makes use of the
garbage collection mechanisms that the Java platform provides.  When a Jython object becomes stale or unreachable,
the JVM may or may not reclaim it.  One of the main aspects of the JVM that made developers so happy in the early
days is that there was no longer a need to worry about cleaning up after your code.  In the C programming language,
one must maintain an awareness of which objects are currently being used so that when they are no longer needed the
program would perform some clean up.  Not in the Java world, the gc thread on the JVM takes care of all garbage
collection and cleanup for you.  This is a benefit of using the Jython implementation; unlike Python there is no need
to worry about reference counting.</p>
<p>Even though we haven’t spoken about classes yet, it is a good time to mention that Jython provides a mechanism for
object cleanup.  A finalizer method can be defined in any class in order to ensure that the garbage collector performs
specific tasks.  Any cleanup code that needs to be performed when an object goes out of scope can be placed within
this finalizer method.  It is important to note that the finalizer method cannot be counted on as a method which will
always be invoked when an object is stale.  This is the case because the finalizer method is invoked by the Java garbage
collection thread, and there is no way to be sure when and if the garbage collector will be called on an object.  Another
issue of note with the finalizer is that they incur a performance penalty.  If you’re coding an application that already
performs poorly then it may not be a good idea to throw lots of finalizers into it.</p>
<p>Below is an example of a Jython finalizer.  It is an instance method that must be named __del__.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__del__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>    <span class="c"># Perform some cleanup here</span>
</pre></div>
</div>
<p>The downside to using the JVM garbage collection mechanisms is that there is really no guarantee as to when and if an
object will be reclaimed.  Therefore, when working with performance intensive objects it is best to not rely on a finalizer
to be called.  It is always important to ensure that proper coding techniques are used in such cases when working with objects
like files and databases.  Never code the close() method for a file into a finalizer because it may cause an issue if the
finalizer is not invoked.  Best practice is to ensure that all mandatory cleanup activities are performed before a finalizer
would be invoked.</p>
</div>
<div class="section" id="summary">
<h2>Summary<a class="headerlink" href="#summary" title="Permalink to this headline"></a></h2>
<p>A lot of material was covered in this chapter.    You should be feeling better acquainted with Python after reading through
this material.  We began the chapter by covering the basics of assignment an assigning data to particular objects or data types.
We learned that working with each type of data object opens different doors as the way we work with each type of data object
differs.  Our journey into data objects began with numbers and strings, and we discussed the many functions available to the
string object.  We learned that strings are part of the sequence family of Python collection objects along with lists and tuples.
We covered how to create and work with lists, and the variety of options available to us when using lists.  We discovered that
list comprehensions can help us create copies of a given list and manipulate their elements according to an expression or function.
After discussing lists, we went on to discuss dictionaries, sets and tuples.  These objects give us different alternatives to
the list object.</p>
<p>After discussing the collection types, we learned that Jython has it’s own set of collection objects that differ from those in
Python.  We can leverage the advantage of having the Java platform at our fingertips and use Java collection types from within
Jython.  Likewise, we can pass a Jython collection to Java as a <em>jarray</em> object.  We followed that topic with a discussion of file
objects and how they are used in Python.  The topic of iteration and creating iterables followed.  We finished up by discussing
referencing, copies, and garbage collection.  We saw how creating different copies of objects does not always give you what you’d
expect, and that Jython garbage collection differs quite a bit from that of Python.</p>
<p>The next chapter will help you to combine some of the topics you’ve learned about in this chapter as you will learn how to define
expressions and work with control flow.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">Chapter 2: Data Types and Referencing</a><ul>
<li><a class="reference external" href="#python-data-types">Python Data Types</a><ul>
<li><a class="reference external" href="#strings-and-string-methods">Strings and String Methods</a><ul>
<li><a class="reference external" href="#string-formatting">String Formatting</a></li>
</ul>
</li>
<li><a class="reference external" href="#ranges">Ranges</a><ul>
<li><a class="reference external" href="#range-format">Range Format</a></li>
</ul>
</li>
<li><a class="reference external" href="#lists-dictionaries-sets-and-tuples">Lists, Dictionaries, Sets, and Tuples</a><ul>
<li><a class="reference external" href="#lists">Lists</a></li>
<li><a class="reference external" href="#id1">Lists</a></li>
<li><a class="reference external" href="#list-comprehensions">List Comprehensions</a></li>
<li><a class="reference external" href="#dictionaries">Dictionaries</a></li>
<li><a class="reference external" href="#sets">Sets</a></li>
<li><a class="reference external" href="#tuples">Tuples</a></li>
</ul>
</li>
<li><a class="reference external" href="#jython-specific-collections">Jython Specific Collections</a></li>
<li><a class="reference external" href="#files">Files</a></li>
<li><a class="reference external" href="#iterators">Iterators</a></li>
</ul>
</li>
<li><a class="reference external" href="#referencing-and-copies">Referencing and Copies</a></li>
<li><a class="reference external" href="#garbage-collection">Garbage Collection</a></li>
<li><a class="reference external" href="#summary">Summary</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="chapter1.html"
                                  title="previous chapter">Chapter 1: Language and Syntax</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="chapter3.html"
                                  title="next chapter">Chapter 3: Operators, Expressions, and Program Flow</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/chapter2.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="chapter3.html" title="Chapter 3: Operators, Expressions, and Program Flow"
             >next</a> |</li>
        <li class="right" >
          <a href="chapter1.html" title="Chapter 1: Language and Syntax"
             >previous</a> |</li>
        <li><a href="index.html">Jython Book v0.1 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2009, Josh Juneau, Frank Wierzbicki, Jim Baker, Leo Soto, ViVictor Ng.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>