Python Tutorial: List Comprehensions Step-By-Step

Поделиться
HTML-код
  • Опубликовано: 19 ноя 2024

Комментарии • 84

  • @major_desync
    @major_desync 6 лет назад +9

    I'd say out of all list comprehension tutorials i looked thru, this one presents that matter in most straight-forward way.

    • @realpython
      @realpython  6 лет назад

      I'm glad you found it straight-forward!

    • @mizurashi2643
      @mizurashi2643 2 года назад

      I was given an extension on my deadline and aren't I glad I came across this. I'll be buying whatever he's selling as a show of support

  • @educationaltechnology8363
    @educationaltechnology8363 Год назад

    programming needs more of you!
    well done you pin-point the exact confusion because most of the videos explain how to make a list comprehension but forget to explain the main components!

  • @mizurashi2643
    @mizurashi2643 2 года назад

    Wow, I've spent a whole week on RUclips and paid resources and this video explains everything I needed to know about iterating through a list.

  • @lorisegovia7995
    @lorisegovia7995 3 года назад +3

    This tutorial really helped me understand list comprehensions. I watched 4 videos and this is the best one by far. Thank you so much!

  • @imxron
    @imxron 7 лет назад +22

    I struggled with this concept previously but this video cleared it up, Thanks!

    • @realpython
      @realpython  7 лет назад +1

      You're welcome! I'm glad the video helped you!

    • @kasonmarcelo1529
      @kasonmarcelo1529 3 года назад

      sorry to be offtopic but does anybody know a trick to get back into an Instagram account??
      I was stupid lost the password. I would appreciate any tricks you can give me

  • @mailrafat
    @mailrafat 4 года назад

    this is by far the best explanation for list comprehension and filtering out there, even the paid videos won't stand a chance. Precisely explained!

  • @MarcPoulin
    @MarcPoulin 7 лет назад +37

    I think list comprehensions would look familiar to someone with an SQL database background since they follow the same pattern as an SQL SELECT statement:
    SELECT expression FROM table WHERE condition

    • @jacobtonna672
      @jacobtonna672 5 лет назад +4

      Ive worked with SQL alot, but seeing this single comment made list comprehensions clikc

  • @androspuddy2
    @androspuddy2 3 года назад

    Thanks a million for the template and breaking it down the way you did!! IDK why other tutorial vids skip this. If they took a moment and did what u did the world would be a better place 👍

  • @matt-g-recovers
    @matt-g-recovers 5 лет назад

    Using a phenomenal app on android to ramp up, but some areas are glossed over a bit too much.
    This was the perfect place to come and the perfect teacher to help me me get it. thanks man!

  • @marcd4144
    @marcd4144 7 лет назад +1

    I really like the way you used mutli-lines in the list comprehension. It looks more readable to me. Ill probably start writing them that way. Thanks for the videos.

    • @realpython
      @realpython  7 лет назад +1

      Thanks! I'm happy to hear it was more readable for you. Happy Pythoning!

    • @randomworld1
      @randomworld1 4 года назад

      Yes, this helped me a lot too.

  • @shyambiradar3271
    @shyambiradar3271 6 лет назад

    I struggled for week to understand . But it cleared in just 14 min . Superb...

    • @realpython
      @realpython  6 лет назад

      I'm glad it helped clear it up for you!

  • @GrandNecro
    @GrandNecro 5 лет назад +1

    writing out the forloop equivilance of the code really helps

  • @AgentJRock805
    @AgentJRock805 4 года назад +1

    Don't forget you can use an ELSE in list comprehension too. Just learned that there are ELSE's in For loops and Try's

  • @abhideepsingh4484
    @abhideepsingh4484 6 лет назад

    way you explained the concept using template was brilliant!

    • @realpython
      @realpython  6 лет назад

      Thanks! I'm glad you enjoyed it.

  • @Raggaliamous
    @Raggaliamous 3 года назад

    Really helpful video, with some great tips thrown in!

  • @CommandD
    @CommandD 3 года назад

    This helped a lot. Thank you.

  • @arsbadmojo
    @arsbadmojo 6 лет назад

    This was definitely one of the best videos on the topic; thank you.

  • @charliegreenaway9111
    @charliegreenaway9111 7 лет назад +1

    Very straightforward and clear explanation. Thanks.

  • @fvgerr
    @fvgerr 4 года назад

    Thanks Dan - excellent video.

  • @CentboyMidnight
    @CentboyMidnight 6 лет назад +3

    I love the listcomprehension syntax but I tested them vs funcs like map(),filter() and funcs are faster

  • @yashhonrao2592
    @yashhonrao2592 6 лет назад

    Clean and clear explanation thanks

  • @BagusSulistyo
    @BagusSulistyo 6 лет назад

    wow thank Man, you make this concept easy to understand

  • @Chevignay
    @Chevignay 4 года назад

    great tuto thks

  • @DARIUSHAZIMI
    @DARIUSHAZIMI 7 лет назад

    Great explanation. Very well done. Thank you..

    • @realpython
      @realpython  7 лет назад +1

      You're welcome! :-) Glad you enjoyed it.

  • @hninyuhlaing835
    @hninyuhlaing835 5 лет назад

    I really thanks to you 'cause I'm clear with that viedo

  • @khalidmohammad5103
    @khalidmohammad5103 5 лет назад

    شكرا دان بدر

  • @anhtuan-nguyen
    @anhtuan-nguyen 7 лет назад +1

    love your videos!

  • @marekoko2083
    @marekoko2083 6 лет назад +1

    Thanks, your video helped me to figure it out! :-)

  • @chrisofnottingham
    @chrisofnottingham 3 года назад

    outstanding

  • @GAPrivaldo
    @GAPrivaldo 5 лет назад

    Nice and clean, thumbs up

  • @BrendanMetcalfe
    @BrendanMetcalfe 4 года назад

    what font is that in the lower panel?

  • @aayushbajaj505
    @aayushbajaj505 5 лет назад

    Thank you soo much i was finding the list comprehension tough u have just started learning python and your vedios are a great help
    And one tinny question which compiler do you recommend...? (For beginners)

    • @realpython
      @realpython  5 лет назад

      I recommend checking out our IDE's and Code Editors guide: realpython.com/python-ides-code-editors-guide/

  • @bryanurizar
    @bryanurizar 4 года назад

    This reminds me of lambda functions I was reading about earlier! I’ve also seen map() used and people say it’s not the “pythonic” way. What does that mean?

  • @invinity3982
    @invinity3982 7 лет назад +1

    wow! thank you!

  • @thoperSought
    @thoperSought 3 года назад

    correct me if I'm wrong, but comprehensions in python are basically pythonic takes on map and filter, right?

  • @sarthak0diwan
    @sarthak0diwan 7 лет назад +1

    thanks a lot

  • @bv-9157
    @bv-9157 3 года назад

    how do you use if/else in list comprehensions ?

  • @VaderFuntime
    @VaderFuntime 7 лет назад

    Great video. Which IDE is it?

    • @realpython
      @realpython  7 лет назад

      Thanks! I mainly use Sublime Text.

  • @imyashkale
    @imyashkale 4 года назад

    how i can get same terminal look like you

  • @lylez00
    @lylez00 4 года назад

    My opinion is that we should only use small list comprehensions. They're not going to be very maintainable otherwise.

  • @Alpacastan21m
    @Alpacastan21m 4 года назад

    How do we convert the result/return statement of a list comprehension to a boolean?

    • @AgentJRock805
      @AgentJRock805 4 года назад +1

      Bool(), All() as well you can use Else's in the list comprehension for an either-or when getting a list/multiple *args of Booleans

  • @ragnarlothbrok367
    @ragnarlothbrok367 5 лет назад

    Lately I've tried to use this with two arguments but Im failing : [i,x for i,x in enumerate(my_items)]. Can this be done somehow?

    • @Carismaticchiic
      @Carismaticchiic 5 лет назад

      Ragnar Lothbrok if you surround with [] around i,x it will work , how ever it will create list of list, if that is what you are looking for. … Suresh

    • @AgentJRock805
      @AgentJRock805 4 года назад

      enumerate doesn't use a second variable

  • @innershapes
    @innershapes 5 лет назад

    what x * x stands for? are they previously set variables?

    • @nadeemhusain3428
      @nadeemhusain3428 5 лет назад

      I'll try to explain, but if someone else wants to jump in it would be much appreciated. X is "loosely" defined in the two lines of code. Given: squares = [x *x for x in range(10)] in lames term we're saying , " for all the x's in the range of 10, multiply x by itself." X is the range of numbers from 0-10, which is why you see when the code is ran the resultant is [0,1,4,9,16,25,36,49,64,81]. hope this clears it up a bit

  • @justgivemethetruth
    @justgivemethetruth 6 лет назад

    Here is your example from your website of a list comprehension:
    squares = [ x * x : for x in range( 10 ) ] which returns the list [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 91 ]
    First, there is a lot of convoluted python stuff in here, and as a beginner to python that likes a lot of what I see, this is perlish in its obtuseness. Yeah, I know, why don't I go invent my own globally accepted programming language, but ignoring that, this takes a lot more brain bandwidth to look at, decipher, and debug if something goes wrong.
    Why not "x * x for x in range( 10 )" as a legitimate phrase, but this does not work, and then the [] brackets just casting the results into a list if they are not already?
    Where does it actually become a win, if it actually does, and that would be where you want to aim your video, in my opinion. This does nothing to motivate me or make me want to use list comprehension or respect python more.
    Plus, what the fuck does "list comprehension" even mean. God I hate BS language like that. Why not "list generation" or "list calculation", or something actually helpful and descriptive. And I am deliberately using profanity because the basics of python are so simple and elegant ... almost brutally elegant, so why the disruption in the style - it is annoying?
    Do languages that get to the point where they have wink at the all-knowing programming insiders and create deliberate obfuscation really have to do that. What is the reason for this. The extra baggage and confusion with no real gain this adds to python shows really bad judgement, unless there is just something I am not seeing, other than the perverse pleasure some programmers get from obfuscation.

    • @AgentJRock805
      @AgentJRock805 4 года назад

      You can use sum() join() bool() all() map() and many more functions on lists.
      That said list comprehension is pretty easy to read. especially the basic ones like this. Want to have some fun go check out lamdas!
      Python is pretty much the easiest language to understand. Go ahead and write your longhand, this is just the surface of any language though!

  • @user-he4ef9br7z
    @user-he4ef9br7z 4 года назад

    why use list comprehensions instead of map and filter , which is faster?

    • @christophercarr5865
      @christophercarr5865 3 года назад

      I think it comes down to list comprehensions being easier to read -- and being considered more "Pythonic" by Pythonistas. The call to map() is more associated with the functional programming paradigm.

  • @mintybidness6614
    @mintybidness6614 7 лет назад

    can you do x*x for i in range(10)? it drives me crazy tutorials are never specific

    • @realpython
      @realpython  7 лет назад

      Why not just try it out? (Yes, you can do x*x)

    • @mintybidness6614
      @mintybidness6614 7 лет назад

      Why not show examples with more than one variable or is that too hard.

    • @ernman681
      @ernman681 6 лет назад

      You can not
      That would be like
      Result = []
      For i in range(10):
      Result.append(x*x)

    • @fvgerr
      @fvgerr 4 года назад +1

      @@mintybidness6614 You can't do x*x for i in range(10). It needs to be x*x for x in range(10)

    • @AgentJRock805
      @AgentJRock805 4 года назад

      Yes you can. You just need an x variable. It would give you the same answer over and over again though. If you wanted you could write...
      [x*i for i in range(10)]

  • @BtsRifer
    @BtsRifer 3 года назад +1

    If you want to use an if-else logic in a list comprehension, the tamplate is:
    [expression1 if condition1 else expression2 for value in collection]
    e.g.
    [int(x ** (1/2)) if x ** (1/2) % 1 == 0 else x * x for x in range(20)]

  • @vishalvashistha
    @vishalvashistha 6 лет назад

    I tried your example, but I end up with different answer, I don't know what is mistake. See these two codes.
    # first code
    s1 = 'mit u rock'
    s2 = 'i rule mit'
    print(s1)
    str = [print('common alphabet') for char1 in s1 for char2 in s2 if char1 == char2]
    # second code
    s1 = 'mit u rock'
    s2 = 'i rule mit'
    for char1 in s1:
    for char2 in s2:
    if char1 == char2:
    print('common alfabhates')
    break

    • @muhammadnajamulislam2823
      @muhammadnajamulislam2823 6 лет назад

      s1 = 'mit u rock'
      s2 = 'i rule mit'
      common_alphabets = [char for char in set(s1) & set(s2) ]
      print(common_alphabets)
      output:
      ['m', 'u', 'r', ' ', 't', 'i']

  • @bradleyhamilton5969
    @bradleyhamilton5969 4 года назад

    Now do strings!

  • @philiphackman9676
    @philiphackman9676 5 лет назад

    How to Loop through a list of names, for each name lookup their age in a dictionary and print the name, age?

    • @realpython
      @realpython  5 лет назад

      Check out our loop tutorials: realpython.com/search?q=loop

    • @AgentJRock805
      @AgentJRock805 4 года назад

      [k, v for k, v in dict.items()]

  • @nurshah816
    @nurshah816 6 лет назад

    why there are 5 dislikes ?