## Lists [ HELP ]

A forum for general discussion of the Python programming language.

### Lists [ HELP ]

def cool(x):
c = 0
while c < x:
print "hello word"
c = c + 1
cool(2)
Result:
"hello word"
"hello word"

Question: How can I transform this, into a list ? like ["hello word", "hello word"]
GabrielSilva

Posts: 8
Joined: Mon May 20, 2013 12:20 am

### Re: Lists [ HELP ]

we will be moving to python-forum.io on October 1 2016
more details here

metulburr

Posts: 2244
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

### Re: Lists [ HELP ]

Could you give me an example?
GabrielSilva

Posts: 8
Joined: Mon May 20, 2013 12:20 am

### Re: Lists [ HELP ]

I could, but I won't, not until you use code tags
we will be moving to python-forum.io on October 1 2016
more details here

metulburr

Posts: 2244
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

### Re: Lists [ HELP ]

You're a good professor.
GabrielSilva

Posts: 8
Joined: Mon May 20, 2013 12:20 am

### Re: Lists [ HELP ]

Code: Select all
def cool(x):
c = 0
while c < x:
print "hello word"
c = c + 1

cool(2)
Result:
"hello word"
"hello word"

What I want is ["hello word", "hello word"]

And, sorry for the misunderstand.
GabrielSilva

Posts: 8
Joined: Mon May 20, 2013 12:20 am

### Re: Lists [ HELP ]

What I want is ["hello word", "hello word"]

instead of printing the string 'hello world', just append that string to a list, with the append() method
we will be moving to python-forum.io on October 1 2016
more details here

metulburr

Posts: 2244
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

### Re: Lists [ HELP ]

Code: Select all
def cool(x):
lst = []
c = 0
while c < x:
s = "hello word"
lst.append(s)
c = c + 1
return lst

def cool1(x):
'''A better way'''
s = "hello word"
return [s for i in range(x)]

def cool2(times, string):
'''A better way with arguments'''
return [string for i in range(times)]

Test.
Code: Select all
>>> cool2(5, 'hello world')
['hello world', 'hello world', 'hello world', 'hello world', 'hello world']
We will be moving to python-forum.io on October 1 2016

snippsat

Posts: 1251
Joined: Thu Feb 21, 2013 12:04 am

### Re: Lists [ HELP ]

Code: Select all
cool = ['hello world'] * 2
print cool

['hello world', 'hello world']
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

Yoriz

Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK