0

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 ,

4
  • 2
    List comprehension is not for executing for loop in single line, you are doing it totally wrong. You should read more about comprehensions Commented Dec 31, 2017 at 12:48
  • What exactly do you mean? What would be "useful"? What output were you expecting?! Why not just print(list(word))? Commented Dec 31, 2017 at 12:50
  • i sprecified that this is an example code (try and try) Commented Dec 31, 2017 at 12:57
  • But what does that mean? If you don't actually have a goal you're failing to reach, the question is unanswerable. If you're just experimenting, what about this has surprised you? Commented Dec 31, 2017 at 13:00

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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']

Comments

0

You could simply do -

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

or

list1 = [w for w in word]

2 Comments

So i can't add print to w -here- for w..?
Well, then Moinuddin's answer is better suited in this case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.