Page - 105 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 105 -
Text of the Page - 105 -
5.1 ListsandTuples:AlternativestoArrays 105
The elements of the list x:
hello
4
3.14
6
List Comprehension There is a special construct in Python that allows you to
run through all elements of a list, do the same operation on each, and store the
new elements in another list. It is referred to as list comprehension and may be
demonstratedas follows:
In [1]: L1 = [1, 2, 3, 4]
In [2]: L2 = [e*10 for e in L1]
In [3]: L2
Out[3]: [10, 20, 30, 40]
So, we get a new list by the nameL2, with the elements10,20,30 and40, in that
order.NoticethesyntaxwithinthebracketsforL2,e*10 for e in L1signals that
e is tosuccessivelybeeachof the list elements inL1, andforeache, create thenext
element inL2bydoinge*10.Moregenerally, thesyntaxmaybewrittenas
L2 = [E(e) for e in L1]
whereE(e)meanssomeexpression involvinge.
In some cases, it is required to run through 2 (or more) lists at the same time.
Pythonhasahandyfunctioncalledzip for thispurpose.Anexampleofhowtouse
zip isprovidedinSect.5.5 (file_handling.py).
SomePropertiesofTuples Weshouldalsobrieflymentionabout tuples,whichare
very much like lists, the main differencebeing that tuples cannot be changed. To a
freshman, it may seem strange that such “constant lists” could ever be preferable
over lists. However, the property of being constant is a good safeguard against
unintentional changes. Also, it is quicker for Python to handle data in a tuple than
in a list, which contributes to faster code.With the data fromabove,we may create
a tupleandprint thecontentbywriting
x = (’hello’, 4, 3.14, 6)
print(’The elements of the tuple x:\n’)
for e in x:
print(e)
Tryinginsertorappend for the tuple gives an error message (because it cannot
bechanged),stating that the tupleobjecthasnosuchattribute.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik