0

This is basic "for loop" pattern printing code as follows:

for i in range (1,5):
    for j in range (i, 5):
        print(j , end='')
    print()

output:

1234
234
34
4

But I want the same as the above output using same logic using the List Comprehension.

for list Comprehension.

I tried :

[print(j,end='') for i in range(1,5) for j in range(i,5)]

and output is:

1234234344
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    **don't use list comprehensions for side effects** – juanpa.arrivillaga May 27 '20 at 23:32
  • Nothing in you comprehension corresponds to the lone `print()` of the loop code, but as others have said -- it is a bad idea to use list comprehensions for side effects. – John Coleman May 27 '20 at 23:33
  • 5
    The really important thing to understand is that *list comprehensions **are not** for loops*. They are functional programming constructs designed to apply mapping/filtering operations over iterables to produce a list. They are *declarative constructs*. For-loops are basic control-flow statements, they *are imperative constructs*. Two different paradigms, and you shouldn't think of a list comprehension as "just a single-line for loop" at all – juanpa.arrivillaga May 27 '20 at 23:40
  • Thank you for your insight into the concept. I'll keep it in mind.@juanpa.arrivillaga,@John Coleman – Sheshank Ranaware May 31 '20 at 12:30

2 Answers2

2

Don't use a list comprehension for side effects, use a plain for-loop instead, i.e. your original code.

But here's how you would do it, by using unpacking instead of a second loop:

[print(*range(i, 5), sep='') for i in range(1, 5)]

So you could do this instead:

for i in range(1, 5):
    print(*range(i, 5), sep='')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

You can approach this by using a function instead :

def myfn(i):
    for j in range(i,5):
        print(j,end='')
    print()


[myfn(i) for i in range(1,5) ]
Tarek AS
  • 187
  • 13
  • 3
    I said this in my answer but I'll say it here too: [don't use a list comprehension for side effects](https://stackoverflow.com/a/5753614/4518341) – wjandrea May 27 '20 at 23:36
  • I just offered this answer if there is a reason behind asking the question.. otherwise Yes don't use the list comprehension approach! :) – Tarek AS May 27 '20 at 23:46
  • @Tarekas, Thanks for the solution. It gave me one more approach. But I was mainly looking for a list comprehension concept. – Sheshank Ranaware May 31 '20 at 12:38