[Tutor] How can I replicate a list in a for loop

Suresh Kumar suresh852456 at gmail.com
Wed Feb 4 10:46:51 CET 2015


here is the sample code
>>> import itertools
>>> import string
>>> var=[]
>>> for i in string.ascii_lowercase[0:5]:
          var.append(i)


>>>print var
['a', 'b', 'c', 'd', 'e']
>>> length=int(raw_input("enter the length of random letters you need "))
enter the length of random letters you need 2

the user gave two so code should be like this
>>>for i in itertools.product(var,var):
           print i[0]+i[1]
output of code should be like this
aa
ab
ac
ad
ae
ba
bb
bc
bd
be
ca
cb
cc
cd
ce
da
db
dc
dd
de
ea
eb
ec
ed
ee
based on the user given input of length i need to add var in for loop
if 3 given
>>>for i in itertools.product(var,var,var):
           print i[0]+i[1]+i[2]
if 4 given
>>>for i in itertools.product(var,var,var,var):
           print i[0]+i[1]+i[2]+i[3]
like this i need to get

i tried var*length
>>>print var
['a', 'b', 'c', 'd', 'e']
>>> var*length
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

if i use the same in for loop
>>>for i in itertools.product(var*2):
    print i[0]+i[1]



Traceback (most recent call last):
  File "<pyshell#16>", line 2, in <module>
    print i[0]+i[1]
IndexError: tuple index out of range

so i need to use many if blocks based on user input which makes my code
very lengthy

thanks in advance

On Wed, Feb 4, 2015 at 1:33 PM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

> On 03/02/15 22:51, Suresh Nagulavancha wrote:
>
>> This is my sample piece of code (not full code of my original code just
>> sample of it)
>> I am using python 2.7
>> Import itertools
>> var=[1,2,3,4,5]
>> Length=int(raw_input("length of possible numbers required"))
>> #This is for length of 3 chars
>> for i in itertools.product(var,var,var):
>>        print i[0]+i[1]+i[2]
>>
>>
>> Here what is my problem is i am unable to replicate the list based
>>
> >  on the user input i tried var*length but it is creating a new
> > single list with repeated values , how can i solve this problem??
> > I want the same original list to be used
>
> Sorry, I couldn't follow that. Can you provide some sample data,
> some inputs and some outputs to show what you expected and what
> you got?
>
> tia
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list