How to create a list of x elements counting by 2 in Python -


i'm taking introductory python course, question might pretty easy of all. assignment i'm working on introducing lists. given variable b2 = 5 , tasked using b2 create list c2 such c2 = [0, 2, 4, 6, 8] has b2 number of elements , counts 2. how this?

lets break down problem. first let cover how lists created in python.

#will create list variable c2 = []  

each list variable has append method can readily use. in event need add first element list, append list contains no values.

c2.append(value) 

the thing is, problem want automatically increment counter , place new value, without having hard code each value list. how solve problem if decide hardcode.

c2.append(0) c2.append(2) c2.append(4) c2.append(6) c2.append(8) 

now reason question gives value b2 = 5 because limit, want loop, increment counter value of 2 until have incremented counter 2 5 times.

increment of counter can done such:

b2 = 0 b2 =+ 2 #or numerical value increment #b2's new value 2 if print it.  

i assume have covered loops in course taking. take info covered , place them loop, using b2 limit, knowledge of increment 2 every time loop comes around, , append new counter value list.

if want go ahead , update code think answer , can work through it, questions feel free commend , can go on then.

there faster ways of answering question such as:

c2 = range(0,b2*2,2) 

the range function works this. range() can take 3 parameters:

  1. start: staring number in sequence
  2. stop: generate numbers to, not including number, hence why multiply b2 * 2 in order generate numbers 10 not 10 leaving last number @ 8 due next parameter.
  3. step: difference between each number in sequence

    range(start,stop,step)

but assume problem wants familiar using loops, list functions, , operators.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -