# List Comprehensions

# List Comprehensions

gkeswani92 + 50 comments `x, y, z, n = int(input()), int(input()), int(input()), int(input()) print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])`

omalsa04 + 24 comments Looks good, but to avoid those repetitive input calls you could do something like:

`x, y, z, n = (int(input()) for _ in range(4))`

gkeswani92 + 1 comment Thanks for the input. Will use this from now! :D

annnguyen + 11 comments Please explain for me why you use

`range(4)`

santhoshreddy923 + 0 comments did you got the output for the above one by using list comprehension?

longdangvn88 + 0 comments This expression is used for reducing the repetitive statements in reading the inputs from console.

naseer_shah + 0 comments [deleted]sohail_shaukat_ + 1 comment range(x,y) will create a range of elements from x to y-1 if only one parameter is passed x is assumed to be 0 so range(y) will create elements in range from 0 till y-1

so here range(4) will create a range which includes 0,1,2,3 hence the loop will iterate 4 times as there are 4 elements

himalayanram_it + 0 comments can you write the complete code snippet using the range(4), I'm getting error. Thanks!

mrrahulgupta0096 + 0 comments it will take 4 inputs i.e from 0 to 3...

gyash919 + 0 comments because we have four variables x,y,z,n

sharmaakhil1998 + 0 comments because there is 4 inputs ! hope you understand

ajaybabuproai3 + 0 comments he want to take input of 4 numbers so in range it counts from 1 then x later until 4 means till n

kaviin27 + 0 comments to get 4 inputs. we are looping the input().

saurabhtumane600 + 0 comments @annguyen bcz its starts from 0 end to 3

AvinashMahanthi + 0 comments it's because since it has to take 4 inputs for the first iteration it takes the 'x' input and for second it takes 'y' similarly for third it takes "z" finally foe third it takes "n"

paul_schmeida + 4 comments Great tip! BTW is there any reason for using '_' as the dummy variable? What's wrong with using letter, for example 'i'?

gkeswani92 + 3 comments _ is used to signify that even though something is being returned, we don't plan to use that variable any where.

mukeshsinghbhak1 + 1 comment gives the following error in above code in python 2.7.13 : at 0x7f60c947e910>

desmondwongjunl1 + 0 comments You need to put an additional [] in addition to [a,b,c]. Because the output that you want is are lists within a list.

codeharrier + 0 comments It's also an old Perl trick. If you just performed the input command without assigning the data to anything, it was still available in the $_ variable by default.

isaiiswariya + 0 comments [deleted]

vijayvijart284 + 0 comments It just like a while loop (Ex: while(a<5)) . If we need to store in the seperte varible you can use like this x,y,z,a = (int(input()) for n in range(4). It will be stored seperatly

gustavs405 + 0 comments no (lol u w8ted 3yrs 4 answer ;D)

sep2001aryan + 0 comments it depends on programmer what to choose , its your wish

motox2 + 1 comment just a small suggestion ..the 4 in for loop will be n+1

AbhishekVermaIIT + 0 comments N is the number to compare the sum of x, y, z. The loop should actually have 4, as mentioned, for the inputs : x,y,z & n.

newmocart + 7 comments in py2 can be w/o int()

x,y,z,n = [input() for i in range(4)] print [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a+b+c != n]

bhosalekv + 1 comment Nice solution

deepakumar50136 + 3 comments WHAT IS THE 4 INDICATES HERE

sravan234 + 0 comments range(4) indicates 0,1,2,3 i.e the numbers we have given are allocated to the x,y,z,n respectively

desmondwongjunl1 + 0 comments 4 input() s

kumarvadivel1999 + 0 comments cuboid has 4*2 vertices

nick3499 + 0 comments [deleted]karangandhi545 + 3 comments what is the reason for x+1 y+1 and many more

elli0t_4lders0n + 1 comment In simple words it signifies that the range is inclusive of max limit

Alagu5 + 0 comments like the control statement

tpgreene + 1 comment range() is inclusive of the first number (which is 0, by default), but exclusive of the last one. So "for i in range(5): print i" will give you 0,1,2,3,4 (but not five). In this case, we want to also include the number given, hence the +1. The 0 for the first part range(0,5), is optional, since we are starting at the beginning.

animesh_jaiswal + 0 comments thanku

shashikantching + 0 comments in python iteration occurs one less than the give variable

anshul_s_panwar + 0 comments why does this code run only for python 2 and not python 3?

amrit55 + 0 comments you need () bracket outside the print

sairamyalinga + 0 comments It doesn't work on py3 right! Why?

alfredocambera + 1 comment Doesn't work on python3.5

akik22 + 0 comments [deleted]

NervousBlakedown + 1 comment I'm using this one line, but my compiler reads "wrong answer". Am I missing something? What else do I need to write?

vammu920 + 0 comments u didnt arrange the list in lexicographic order

NervousBlakedown + 1 comment Disregard, I figured it out.

vammu920 + 0 comments can u send the solution

kumarharsh + 1 comment I am a newbie to python and its not clear to me. WHY 4? And how the variable iterate from 0 to 1.

Code_Lord + 0 comments range(4) means range(0,4) that is 0,1,2,3 which is because we ahve to read 4 inputs Read list comprehensions for more. It is an easy way to build a list.

rahul_rowthi + 0 comments How is this syntax even valid. Just wondering.

aonomike + 1 comment what does for _ in range(4) do ? what's the significance of the underscore? @omalsa04

codin_kyle + 0 comments I think that _ is used as a dummy variable name. Since it's meaning isn't really significant the name can be something representing that.

Dev_prasad + 0 comments [deleted]Highlander_Monk + 0 comments Wow nice way to take inputs.

[deleted] + 0 comments [deleted][deleted] + 0 comments [deleted]sekououattara9 + 0 comments why range (4) ???

hsu_ryan + 1 comment why do i need to add parentheses around

`int(input()) for _ in range(4)`

in order for this code to work?

sep2001aryan + 0 comments coz you have to assign these values to different variables

ayushayush591 + 1 comment in place '_' you should 'n'

sep2001aryan + 0 comments both methods are coprrect :0

mrjomp + 0 comments Makes code less readable, also that doesn't improve time complexity or space complexity so I don't find it that useful other than save some lines of code :S

michaellan202 + 0 comments You can also take in the entire buffer at once with

from sys import stdin x,y,z,n = map(int, stdin.readlines())

benedictwaiharo + 0 comments or you could use functions

WhatsupLucia + 0 comments x, y, z, n = (int(input()) for _ in range(4)) isn't working for me. I'm getting a EOF when reading line error.

Abe10 + 0 comments @vorayash0510, this is great!

ilhan_syed + 1 comment why do you use the '_' symbol?

sohail_shaukat_ + 0 comments _ is used to indicate that you don't care about the value of the variable, and are just using as a placeholder.

"_" is a valid variable name.

So for example if we need an instruction to be executed thrice, one way of writing would be '''

`total = 0 for i in range(3): total += 1`

'''

but since we're not using variable 'i' inside the loop, value of 'i' doesn't matter

hence same could be written as,

'''

`total =0 for _ in range(3): total += 1`

'''

p.s.

even better way would be

'''

`total = 0 for _ in iter(range(3)): total += 1`

'''

But that's a different story :P, I hope this helps ! :D

aa1992HackerRank Admin + 9 comments nice solution. But instead of range[0,x] you could do

`print ([[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n ])`

ericali + 0 comments clever!!!

rajasekhariiith + 0 comments [deleted]SuperGogeta + 3 comments Trade three +1's for a +1 and a -1 at the right place :P

x, y, z, n = (int(raw_input())+1 for _ in range(4)) print [[a,b,c] for a in range(x) for b in range(y) for c in range(z) if a+b+c!=n-1]

zhangqunshi + 0 comments although this method is more simple, but it not easy to understand.

yidingyang1027 + 0 comments great!

usaliev + 0 comments I liked this method compared to other's.

james_niroo + 0 comments really like this solution. simple and easy to read

abedsarkil12 + 0 comments [deleted]Dvcks + 0 comments [deleted]shashiwalker + 0 comments i have done the same thing by its not working ,says invalid syntax

mohana2291 + 0 comments Simple and efficient than mine !! Thanks

shankarydv8010 + 0 comments will you please explain the program implementation program?

rachitajitsaria1 + 1 comment Hey, I have heard that int(raw_input()) is faster.

maximshen + 0 comments raw_input() was renamed to input() in python 3

boler + 0 comments [deleted]rahatchd + 2 comments Can you tell me how python carries out list comprehension internally? How come this generates lists in lexicographic increasing order (i.e z increases first, then y, then x)?

Ryukerg + 7 comments It is in lexographical order due to the nature of the loops. Spaced out it looks somewhat like

`for a in range(x+1): for b in range(y+1): for c in range(z+1): if a + b + c != n: print(stuff is here)`

We start at [0,0,0]. Then c will increment to get to [0,0,1] When c hits [0,0,z], we get [0,1,0] as the next in the loop. This pattern continues and gives us the lexographical ordering required of the output.

BHEEMKUMAR + 0 comments it's very helpfull to understanding that what is actualy asking

masudraj6 + 0 comments Thanks for your solution, now we understand how it's word.

nick3499 + 0 comments [deleted]dangducbac_hust + 1 comment Here is my soltion with your sussgestion:

empty_list = [] for a in range ( x+ 1): for b in range ( y + 1): for c in range ( z + 1): #logic code if (a + b + c != n) : empty_list.append([a,b,c])

print(empty_list)

sheetalparmar899 + 0 comments But my program is not working properly.

krzysztof_jerzy1 + 0 comments Thank you, I really wondered on how it works.

borad_sarita + 0 comments really much helpfull in understanding

nick3499 + 0 comments [deleted]

SanjayDeepu + 0 comments This solution is good! Utilising list comprehension to a good extreme.

trinadhkoya + 0 comments Not reqired to put input() for each variable .just call the input for _ in range(no of variables); see here

a , b = int (input()) for _ in range ( 2 ):

bennetryan + 1 comment Thanks for sharing your elegant code. I'm a newbie to Python, its great to see such beautiful code :)

trinadhkoya + 0 comments to whome you added the comment :)

jonobjornstad + 0 comments great code

andras_lengyel + 1 comment I don't like these "direct print" solutions. In my opinion the problem stated to

*create*a list then*print it*, not just print something in a list. In other words in your solutions the list itself doesn't exist, can not be used later, it just collected when printed out. What do you think?andras_lengyel + 0 comments OK, I found the answer! I can put list = instead of printoing out, then print the list. It wasn't clear for me three for loops output is collected in a list, so no need for any append tricks!

ignacio_ch + 2 comments Nice answer. As an alternative, to avoid multiple for loops you can use product:

combinations = list(product(range(x+1), range(y+1), range(z+1))) print([list(a) for a in combinations if sum(a) != n])

davidkobilnyk + 0 comments from itertools import product

18vidhyasagar + 0 comments how is this working?

raspletin + 0 comments it is not solution, as question was to form list comperhention. You just put out data to screen in right format, no list comperhetion created

pH03nYx + 1 comment Could someone explain to me what, exactly, this code does (like, statement-by-statement)(other than the input part I understand that I mostly mean the list comprehension)? I sort of have a basic understanding of how it works, but having some trouble wrapping my head around list comprehensions and how exactly the work. Mostly the "for a in range(0,x+1)" parts. What exactly does that do? Why is it (0,x+1)? Thanks in advance.

madaharishreddy + 0 comments just for curiosity, why you are using range(0,x+1) in the print function?

ldhyim568 + 0 comments why do you need two square brackets? Can someone explain this to me?

janu_s + 1 comment hello.. I tried to do as u said. But it is showing syntax error.

kumar_student101 + 0 comments from itertools import product

print([list(each) for each in product(range(x+1),range(y+1),range(z+1)) if sum(each)!=n])

[deleted] + 0 comments I'm new to python, but how come nobody seems to be using ":" after their for loops. You don't even use one for the if loops at the end.

infnity + 0 comments When you were using for statement inside the print statement you didn't use a colon infront of the for statement???? why was that

chefyunfei + 1 comment exactly what I had, expect I left the 0 implicit. Is it good practice to make the range explicit?

kumar_student101 + 0 comments For this program it is fine. But in real time data range may not be static.

mehdi_jafaree131 + 0 comments no need for 0 in range

Headhunter1 + 0 comments how is list comprehension workin here?

Winkey + 0 comments Good one!!!!

achintya0210 + 0 comments I have no idea what is the syntax error that the compiler is showing repeatedly on (a+b+c)!=n

naveenyadav9515 + 0 comments Thank you very much bro..... i am new to python... initially i din't understand your code but i realized after converting it into normal form. x, y, z, n = int(input()), int(input()), int(input()), int(input()) for i in range(0,x+1): for j in range(0, y + 1): for k in range(0, y + 1): if i + j + k !=n: print([i,j,k])

aliajunisarshaf1 + 0 comments Thanks for your solution!

hakeshkumark + 0 comments why x+1?

mosinpinjar049 + 0 comments wrong answer

yuvi1690 + 2 comments This is not usable with python 3 , shows error..!!

santhoshreddy923 + 0 comments i got it in google chrome but not in edge i dont know the issue

santhoshreddy923 + 0 comments thank you for commenting

nikhilbellad99 + 0 comments this code does print in lexiocgraphy format but not the expected out

thakkarvaibhav7 + 0 comments if possible, can you please explain me how it will how

abhisikta_mishr1 + 0 comments why range x+1

bhupeshjain + 0 comments can be :

print([[a, b, c] for a in range(x + 1) for b in range(y + 1) for c in range( z + 1) if a+b+c != n ])

rnamaye175 + 1 comment print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])

sir can you explain this line

sep2001aryan + 1 comment @rnamaye this line print the value of a,b,c from 0 to x+1 , y+1 ,z+1 respectively if the sum (a+b+c) is not equal to the n

rnamaye175 + 0 comments okay sir and one more doubt regarding to that only (a+b+c) !=n

kavithamidde888 + 0 comments Thanks Bro

JaydeepBorkar + 0 comments [deleted]kunal_rana_vps + 0 comments can u explain me the working of this code ??

jkgoyal029 + 0 comments can anyone explain how this code works from print.........

lakshmanpraveen1 + 0 comments Y aare we supposed to run the loop from 0,x+1

yashikesarwani18 + 0 comments why range(0,x+1) ? why x+1 and not x ?

Rahul_7f + 0 comments why range 0 , x+1

Rahulpareek9250 + 0 comments thank you

mogra_nitin14 + 0 comments @gkeswani92 - can you please confirm what will be the order of complexity for this code ? is this still considered a nested loop or is this considered linear ?

tawadeviniket9 + 1 comment x, y, z, n = int(input()), int(input()), int(input()), int(input()) print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if x + y+z != n ]) i have written the above code,but it is counting the a+b+c= n entries also..can someone explain why?

sohail_shaukat_ + 0 comments Hi Niket, The problem lies in your if condition, you're running loop with a,b,c but your comparing with it with input limit variables. Try the below snipped of code I'm sharing and this should work :

x, y, z, n = int(input()), int(input()), int(input()), int(input())

print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if (a + b + c) != n ])

amanthapliyal3 + 0 comments Still what about its complexity?? Its still O(n^3)

soniyaarockiya + 0 comments is there a way to reduce the number of 'for in range' ?

ilhan_syed + 0 comments will you please explain to me the logic in writing "x+1" , "y+1" and "z+1"?

Parthbunny7 + 0 comments Can you explain me this logic

harshajavalkar28 + 0 comments But still time complexity is MORE

neha1304_v + 0 comments nice solution,but for input we can also use

x,y,z,n=map(int,input().split())

ashish2398negi + 0 comments [deleted]

cassio_augcs + 2 comments Ok, after hours trying to actually understand the problem, and after trying to solve it in reverse, I hope to bring some clarity for those who are having a hard time trying to solve or to understand what exactly needs to be done and what the codes posted here are actually doing. I did this using

**Python 3**.Ignoring the mathematical terms, the problem wants you to

**create a list in a concise way**(that's called 'List Comprehension'). Which consists on**creating a list using 'for' and, possibly, 'if'**(in case you want an extra condition in that list).In this case, it asks you to create multiple lists using 3 'for' clauses: i, j and k. In each theses clauses you will choose an range to vary from 0, which will be called x (for clause i), y (for clause j) and z (for clause k).

The challenge here is to create every possible list that will show all values from the chosen ranges (x, y and z) in a way that the the predecessor number will change to the next value from the range only AFTER the successor number shows all it's values first.

**Before trying an example, first a reminder:**As seen in previous challenges, in a 'for' clause, the value of a range will vary (as a standard) from 0 to the predecessor number in that range. I.E.: for A in range(2): will output 0 and 1, but not 2.Now, let's try to solve it with a simple example: I'll set both, x, y and z to 1, just to make it easier.

This is the formula in a clearer way (not in a single line, but I believe it's best for beginners to understand):

listijk = [] #an empty list to be filled as following for i in range(x + 1): #it will output 0, and will only output 1 after the next conditions ('for j' and 'for k') are met. for j in range (y + 1): #it will output 0, and will only output 1 after the next condition ('for k') is met. for k in range (z + 1): #it will output 0 and then 1. listijk.append([i,j,k]) #it will add i, j and k values to the list print(listijk) #print the list properly filled

**(copy and paste the code in an code editor for clearer reading)**In the example above, that's what will happen behind the scenes, in this exact order:

i = 0, j = 0, k = 0

i = 0, j = 0, k = 1

i = 0, j = 1, k = 0

i = 0, j = 1, k = 1

i = 1, j = 0, k = 0

i = 1, j = 0, k = 1

i = 1, j = 1, k = 0

i = 1, j = 1, k = 1

It will print exactly like that:

`[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]`

As you can see, it made 8 different output variations.

**Now, to the last part of the problem...**It creates one extra condition: it will NOT print the outputs which the sum of the values inherited by i, j and k equals to the integer 'n'.So, this time, the code will become:

listijk = [] for i in range(x + 1): for j in range (y + 1): for k in range (z + 1): if i + j + k != n: #before printing the result, it will exclude the output which 'i' + 'j' + 'k' is the same as 'n'. listijk.append([i,j,k]) print(listijk)

In this case, let's suppose that 'n' is set to 2:

i = 0, j = 0, k = 0 #will print

i = 0, j = 0, k = 1 #will print

i = 0, j = 1, k = 0 #will print

i = 0, j = 1, k = 1 #will NOT print (1 + 1 = 2)

i = 1, j = 0, k = 0 #will print

i = 1, j = 0, k = 1 #will NOT print (1 + 1 = 2)

i = 1, j = 1, k = 0 #will NOT print (1 + 1 = 2)

i = 1, j = 1, k = 1 #will print

And then, it will print the following 5 outputs:

`[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]`

That's an extense explanation, but I'm just trying to make it as clear as possible for those who, just like me, are having a hard time figuring out what the problem wants and what the codes posted here and in the examples are really doing. Hope it helps someone.

rondina + 1 comment Not wrong, but you have not used list comprehension. Consider a list called 'a' with even and odd numbers. Now suppose you want to create a list 'b' that contains only the even numbers of list 'a'.

One way to do this in the usual way with a loop:

- b = []
- for n in a:
- if n % 2 == 0:
- b.append(n)

Using list comprehension this would look like this single line:

- b = [n for n in a if n % 2 == 0]

The challenge in this problem is creating nested list comprehesions, which can be tricky. See PEP 202.

(Sorry for the broken formatting, but it's not possible to code-format in replies here in HR.)

karanveerkhatra1 + 0 comments Thanks a ton , it's because of you I was able to understand what's required from the problem

GiddyUp + 0 comments Thank you. The problem is actually lacking clearer explaination.

gabobaby + 0 comments The problem states that it wants the output list printed in 'increasing order'. It should be more clear what this means. I initially interpreted this to mean that [1,1,0] would come before [3,0,0] because 1+1+0=2 is less than 3+0+0=3. But this is not the order that the comprehension list method would generate the list. And would likely involve some method of sorting a 3D array that many new users would not know at this point, so I'm assuming this is not what is meant. This problem is not clarified with the chosen example values of x=1, y=1, z=1, and N=2.

The problem could be addressed by just using larger example values, allowing us to infer from the example output which interpretation of 'increasing order' is intended.

scintilla + 2 comments What does N represent? Why should X+Y+Z not equal N? And what do the subscript i's represent? I don't understand the question.

saikiran9194HackerRank Admin + 2 comments @scintilla read the question properly. 0<=Xi<=X same for Yi and Zi.N is specified in the question.

jhub1 + 0 comments I am sooooooooooooo confused with the question holy cow.

ID10TERROR + 1 comment You can't just say "Read the question properly". He said he doesn't understand the syntax of the question.

This is a type of mathematic short-hand that not all of us understand. I for one don't even know what this short-hand is called or I'd look it up myself.

shashank21jHackerRank Admin + 2 comments Try now, I have updated the statement :)

ID10TERROR + 1 comment Thank you for the follow-up shashank21j, your revision to the statement has been helpful, but I still have some questions about the way the question is worded and why.

1.Why must i+j+k not be equal to N and does this mean it can be greater than N?

2.Please define "lexicographic increasing order"

I for one agree that list comprehension in python is a fairly simple subject, the crux of this problem for me however, is bridging the communication gap/understanding the essance of the problem you're asking.

Many people who use your site are self taught in coding and do not have a formal discrete mathematics background.

shashank21jHackerRank Admin + 1 comment i + j + k != N is just an added condition in this problem so you can use 1 if statement inside your list compehension syntax. It can be greater than N as long as i, j and k are in their respective limits.

- Lexicographic order is sorted order where 1, 1, 1 comes before 1, 1, 2 and 2, 1, 2 comes before 2, 2, 1 etc. etc.

ID10TERROR + 0 comments Thanks again shashank21j! :)

dng304 + 0 comments Shouldn't the statement include that X,Y,Z are integers that are possible maximums? It is a fairly important point no? For example dimensions of 2,2,2 given the statement as it currently is, means there is only 1 possible cube with 8 coordinates.

Where as if we said that 2 is the max integer value for X,Z,Y , we can have more than 1 possible cuboid. For example a 1,1,2 cuboid.

mike_kinny + 0 comments I have also difficulty understanding the question.

fisher6 + 1 comment print([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if sum([i,j,k]) != n])

Chemical_a5 + 0 comments This comment taught me list comprehension. Thanks for concise answer.

Sort 448 Discussions, By:

Please Login in order to post a comment