Tim
Tim

Reputation: 298

Execute multiple lines with python in one line for loop

I have a loop that appends to new list named list1 and it is working, but how can I add something more like print(x) or anything useful to list1.append(...)?

word="abcdefg"
list1=[]
[list1.append(word[i]) for i in range(len(word))]
print(list1)

I've tried using list1.append(word[i]);print("working") and with ,

Upvotes: 0

Views: 3728

Answers (3)

Derte Trdelnik
Derte Trdelnik

Reputation: 2706

define a function that does "more lines of code" and use it in the comprehension

word="abcdefg"
list1=[]
def add_and_print(character, container):
    container.append(character)
    print("adding", character)
[add_and_print(character, list1) for character in word]

comprehensions should be short and easy to read in the first place, avoid having a complex one, one condition one call and one for statement should be the maximum - if you need a complex looping etc, create a generator

[call(something) for something in some_container if something == foo]

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

As I stated in comment, List Comprehensions are not just for executing for loop in single line. They are very powerful but you need to read about it. You may take a look at: Python List Comprehensions: Explained Visually.

However in your this particular case, all your code is doing is to convert the string to list, and printing it. You may do it in one line as:

>>> print(list("abcdefg"))
['a', 'b', 'c', 'd', 'e', 'f', 'g']

Upvotes: 1

Vikas Ojha
Vikas Ojha

Reputation: 6950

You could simply do -

list1 = [word[i] for i in range(len(word))]

or

list1 = [w for w in word]

Upvotes: 0

Related Questions