python - How to add multiple elements in a list together by index? -



python - How to add multiple elements in a list together by index? -

how add together elements of list index (simple math)?

for example:

a = 123456789 b = a[0] + a[2] + a[6] #does not work print (b)

however, want sort of outcome:

b == 11

you need larn python's types. first, want treat numbers string, create string literal:

a = '123456789'

now need coerce each part of string that's selected integer, int:

b = int(a[0]) + int(a[2]) + int(a[6]) #works!

you can store string list, don't have coerce ints each one:

a = [1,2,3,4,5,6,7,8,9]

or

a = range(1,10) # in python 2 = list(range(1,10)) # in python 3

then

b = a[0] + a[2] + a[6] print(b)

prints 11

and should homecoming true

b == 11

python list elements

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -