Seite - 42 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 42 -
Text der Seite - 42 -
42 2 BasicConstructions
Alistmayalsobecreatedbysimplywriting, e.g.,
x = [’hello’, 4, 3.14, 6]
givinga listwherex[0]contains thestringhello,x[1]contains the integer4, etc.
Wemayaddand/ordelete elements anywhere in the list as shown in the following
example.
x = [’hello’, 4, 3.14, 6]
x.insert(0, -2) # x then becomes [-2, ’hello’, 4, 3.14, 6]
del x[3] # x then becomes [-2, ’hello’, 4, 6]
x.append(3.14) # x then becomes [-2, ’hello’, 4, 6, 3.14]
Notethewaysofwritingthedifferentoperationshere.Usingappend()willalways
increase the list at the end. If you like, youmay create an empty list as x = []
before you enter a loopwhich appends element by element. If you need to know
the length of the list, you get the number of elements fromlen(x),which in our
caseis5,afterappending3.14above.Thisfunctionishandyifyouwant totraverse
all list elements by index, sincerange(len(x))givesyouall legal indices. Note
that therearemanymoreoperationson lists possible thanshownhere.
Previously,wesawhowafor loopmayrunoverarrayelements.Whenwewant
todo thesamewitha list inPython,wemaydo it as this little exampleshows,
x = [’hello’, 4, 3.14, 6]
for e in x:
print ’x element: ’, e
print ’This was all the elements in the list x’
This is how it usually is done inPython, andwe see thate runsover the elements
ofxdirectly, avoiding the need for indexing. Be aware, however, thatwhen loops
arewritten like this, youcannotchangeanyelement inxby“changing”e. That is,
writinge += 2will not changeanything inx, sincee canonlybeused to read (as
opposed tooverwrite) the list elements.
There isaspecialconstruct inPythonthatallowsyoutorunthroughallelements
of a list, do the sameoperationoneach, andstore thenewelements in another list.
It is referred toas list comprehensionandmaybedemonstratedas follows.
List_1 = [1, 2, 3, 4]
List_2 = [e*10 for e in List_1]
This will produce a new list by the name List_2, containing the elements 10,
20, 30 and 40, in that order. Notice the syntax within the brackets for List_2,
for e in List_1 signals thate is to successively be each of the list elements in
List_1, and for eache, create the next element inList_2bydoinge*10. More
generally, the syntaxmaybewrittenas
List_2 = [E(e) for e in List_1]
whereE(e)meanssomeexpression involvinge.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik