Python Tutorial for Beginners 4: Lists, Tuples, and Sets

Share
Embed
  • Published on May 17, 2017
  • In this Python Beginner Tutorial, we will begin learning about Lists, Tuples, and Sets in Python. Lists and Tuples allow us to work with sequential data, and Sets allow us to work with unordered unique values. We will go over most of the methods, learn when to use which data type, and also the performance benefits of each type as well. Let's get started.
    The code from this video can be found at:
    github.com/CoreyMSchafer/code_snippets/tree/master/Python-Lists
    Watch the full Python Beginner Series here:
    thexvid.com/p/PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
    Slicing Video: thexvid.com/video/ajrtAuDg3yw/video.html

    ✅ Support My Channel Through Patreon:
    www.patreon.com/coreyms
    ✅ Become a Channel Member:
    thexvid.com/channel/UCCezIgC97PvUuR4_gbFUs5gjoin
    ✅ One-Time Contribution Through PayPal:
    goo.gl/649HFY
    ✅ Cryptocurrency Donations:
    Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
    Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
    Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
    ✅ Corey's Public Amazon Wishlist
    a.co/inIyro1
    ✅ Equipment I Use and Books I Recommend:
    www.amazon.com/shop/coreyschafer
    ▶️ You Can Find Me On:
    My Website - coreyms.com/
    My Second Channel - thexvid.com/user/coreymschafer
    Facebook - CoreyMSchafer
    Twitter - CoreyMSchafer
    Instagram - coreymschafer
    #Python

Comments • 512

  • Kognito Beatz
    Kognito Beatz Day ago

    20:12 - Tuples section

  • Soumya Ranjan Das

    Thank you Corey for your time and effort. Keep spreading the knowledge.

  • Ali Musa
    Ali Musa 6 days ago +1

    Best resource available to learn Python. I have been searching for 15 days and finally found one. Mostly channels are just to catch the attention and a new comers doesnt know untill the end whether its basic or advance. This instructor exactly know what he is teaching and what needs to be taught here.
    Just keep your pen and note book ready, python is game of 10 videos.

  • Holy Samurai
    Holy Samurai 6 days ago +1

    Hey Corey, i've been trying to figure out a problem for awhile now and i just can't seem to come up with the answer. The .strip()
    method is working but when i use .lower() after .strip() it doesn't fix my problem , During user_inp prompt, i type in 'Hey' with some spaces and it works because of the .strip() added to user_inp , but when i add .lower() after .strip() it prints out the elif statement ("~~ W R O N G!"). I try typing in 'hey' with lowercase and it says wrong even though 'Hey' is in the list_A. Here is my code below, i appreciate any help.


    while True:
    list_A = ['Hey', 'Hello', 'Hi', 'Hello there']
    user_inp = input("Type a word that's in list_A: ").strip()
    # .lower() doesn't seem to work after .strip()

    if user_inp in list_A:
    print("~~ C O R R E C T!")

    elif user_inp not in list_A:
    print("~~ W R O N G!")

    • Holy Samurai
      Holy Samurai 2 days ago

      @strawberryyogurt0 thanks a lot!

    • strawberryyogurt0
      strawberryyogurt0 3 days ago

      @Holy Samurai .... Use .strip().capitalize() I'm a beginner learning python, I came across your comment and wanted to do some investigating myself. The first thing that I did was add print(user_inp) to see "what exactly" the user typed in BEFORE .strip().lower() does their computer thing. It's also great that I came across your comment because I also learned (based on your comment) that I can add multiple functions on the same line, like such text.strip().capitalize(). I also got to learn about .strip()

      SHORT VERSION: with what you're wanting to achieve (this is my understanding):
      # case sensitive, which is why .lower() will always result in the ELIF statement (based on your If statement AND the list_A elements.
      # use .strip().capitalize()
      # don't use .strip().lower()

      # the other "possible" option is to use .strip().title()
      # unfortunately " Hello there " would unfortunately give you a WRONG result (because .title() changes "hello there" to "Hello There" ( your list_A needs "Hello there")
      #.strip().capitalize() .... however would work with Hello there

      user_inp = input("Type a word that's in list_A: ").strip().capitalize()
      print(user_inp, "... this is what is actually typed in by the user")

      text = "the lost puppy found her way back home"
      text.capitalized() ---> "The lost puppy found her way back home"
      text.title() ----> "The Lost Puppy Found Her Way Back Home"

      second_text = "I Love Sports. I Love Coding. Apple Oranges."
      second_text.captialized() --> "I love sports. i love coding. apple oranges."


      LONGER VERSION (BELOW)
      ......................................................................
      (1) print(user_inp, "... this is what is actually typed in by the user")

      while True:
      list_A = ['Hey','Hello','Hi','Hello there']
      user_inp = input("Type a word that's in list_A: ").strip().lower()
      print(user_inp, "... this is what is actually typed in by the user")

      # doing this (adding the print line), I was able to see what the user was exactly typing.
      # after doing test runs, changing .strip().lower() ----> .strip().capitalize() FIXED the issue.
      .......................................................................
      (2) Are you sure you want to use .lower() like so:
      user_inp = input("Type a word that's in list_A: ").strip().lower()

      # because by adding .lower(), that will always result in the ' elif ' statement based on your condition. NOTE: Think about what:

      # .lower() does VERSUS
      # what's in list_A VERSUS
      # IF condition VERSUS
      # case- sensitivity

      #. (it took me a few minutes to figure things out as well; by looking at the 'output' of the print(user_inp) ..
      # list_A has the first letter to all the words in capital (Hey, Hello, Hi, Hello there)
      # by adding .strip().lower() to the ' user input ' , python will convert anything the user typed into lower case.
      # if the user types 'Hey' , .lower() will change it to 'hey' and therefore the statement will go to elif.
      # with .lower() Hello ---> hello ... results in elif statement WRONG
      # with .lower() Hi -----> hi ... results in elif statement WRONG
      # with .lower() Hello there ---> hello there ... results in elif statement
      WRONG

      # NOTE: However, if your list_A = ['hey','hello','hi','hello there'], then .strip().lower() would result in the IF CORRECT statement

      # NOTE: in order to get it to the IF statement, the user needs to types the first letter of each word with a capital letter (Hey, Hello, Hi, Hello there). So unfortunately, .title() would also cause problems (hello there --> Hello There). BUT .capitalize() would be perfect (hello there --> Hello there). The .lower() function changes everything the user typed to lower letters (hey, hello, hi, hello there)

      ............................................................................
      (3) Use .capitalize() instead
      # because .strip().capitalize() will change anything the user types into the proper format (capitilize the first letter even if the user types the first letter with a lower case)
      # .strip().capitalize() ..... gives you want you want (at least from what I've read in your comment)
      # with .capitalize() user input: hello -----> output: Hello (results in IF statement CORRECT
      # with .capitalize() user input: hey -----> output: Hey (results in IF statement CORRECT
      # with .capitalize() user input: hi -----> output: Hi (results in IF statement CORRECT

      # [ Note: also don't use .upper() ... .
      # upper() results in all letter capitlized Hey --> HEY ... Hello ---> HELLO ]
      # with .upper() user input: hello ---> output HELLO (results in ELIF statement WRONG


      #### The following uses .strip().capitalize()

      print("."*50)

      while True:

      list_A = ['Hey','Hello','Hi','Hello there']
      user_inp = input("Type a word that's in list_A: ").strip().capitalize()
      print(user_inp, "... this is what is actually typed in by the user")

      if user_inp in list_A:
      print(" ~~ C O R R E C T!")

      elif user_inp not in list_A:
      print(" ~~ W R O N G!")

    • Sanian Creations
      Sanian Creations 4 days ago

      You are converting the user input to all lowercase, but then it checks if that value is in the list whilst the list still has the words in uppercase.
      To make this work you have to make all the values in the list lowercase. Then any input the user gives will also become lowercase because of the .lower() at the end. Now you can type the words with capitals or not, your user input wil be converted to lowercase anyways and then compared to the list.
      You can also change the elif statement to just else because if "user_inp in list_A" fails then that automatically already means it is not in the list, so you dont have to check for that again.
      while True:
      list_A = ['hey', 'hello', 'hi', 'hello there']
      user_inp = input("Type a word that's in list_A: ").strip().lower()
      if user_inp in list_A:
      print("~~ C O R R E C T!")
      else:
      print("~~ W R O N G!")

  • nora JIN
    nora JIN 14 days ago

    is method a keyword token or identifier token?

  • Rishabh Singh
    Rishabh Singh 14 days ago

    You sound like Donald trump

  • Evolution_Algorithm
    Evolution_Algorithm 19 days ago

    So you can’t pass a list by value only by reference!?

    • Evolution_Algorithm
      Evolution_Algorithm 19 days ago

      Corey Schafer so new_list = old_list.copy() does it. Did I miss this in the video?

    • Corey Schafer
      Corey Schafer  19 days ago

      You can if you copy it.

  • George Billy Kplorfia
    George Billy Kplorfia 21 day ago +1

    Great job! well done. well taught

  • David A.
    David A. 26 days ago

    Very good explanation. But to be honest, this lessons is excellent for Developers, who are very well familiar with development concepts, and starting to switch to Python, nor than developers who just starting to learn development from scratch.

  • Menatoorus
    Menatoorus 28 days ago +1

    I've searched the youtube thick and thin for python tutorials for a week by now. These are the best ones indeed. Thank you my Great Guru.

  • king margie
    king margie 29 days ago +1

    Your videos are great!

  • Alan Tureen
    Alan Tureen Month ago +1

    Many thanks Corey, It is by far the best python tutorial I have ever seen. Informative, comprehensive and just perfect.

  • Catarina Castanheira
    Catarina Castanheira Month ago +1

    in uni

  • Catarina Castanheira
    Catarina Castanheira Month ago +1

    You saved my life !

  • Ms. S R.E
    Ms. S R.E Month ago

    Is there a transcript from this video? thank you.

  • Yashwanth raj
    Yashwanth raj Month ago +1

    Very easy to grasp from your way of teaching. Very well done , Thank you.

  • ProgRAMmer
    ProgRAMmer Month ago

    Day 2 Done 10/1/19

  • Killerkamatis Pogi
    Killerkamatis Pogi Month ago +1

    More power to you good sir.

  • Abdullah Yaqoob
    Abdullah Yaqoob Month ago +1

    good job, the first time I can see the advantage of Sets. keep it going

  • marcus miuccio
    marcus miuccio Month ago

    #check if item is in list and return boolean value (true or false)
    courses = ['history', 'math', 'science', 'gym']
    answer = 'math' in courses
    print(answer)

  • Pran N gowda
    Pran N gowda Month ago +1

    great ......thank you so much..........!😊

  • Khan NORFOLK
    Khan NORFOLK Month ago

    what IDE are you using ???? plz

    • Corey Schafer
      Corey Schafer  Month ago

      Hey There. I use Sublime Text for my tutorials since it's pretty minimalist. I also use VSCode for my day-to-day coding. I made a video on how I set up my Python development environment in both of those editors. You can find those videos here:
      Sublime Text - thexvid.com/video/xFciV6Ew5r4/video.html
      VSCode - thexvid.com/video/06I63_p-2A4/video.html
      Thanks!

  • sarath kumar
    sarath kumar Month ago

    What is the use of empty list,tuple and also sets...give an example for it....???

    • Corey Schafer
      Corey Schafer  Month ago +1

      Sometimes these are returned from functions. If there are no results, then the function may choose to return an empty tuple, set, etc.

  • Ricardo Corral mijares

    Hey there! thank you for this, I was wondering about creating a list with some imputs untilthe value "*" is typed, let me explain: I have to create a list where the user first will write down some int numbers, this should be in a list, and the list will be reciving this numbers until the user types "*", then the list should be closed and the program will show the lenght of the list, which numbers are pairs, and which are not. If some of you could help, ill be really grateful, thank yall. :)

  • Hip Hop Hooligan
    Hip Hop Hooligan Month ago

    I don't get something. Sometimes the name of the method is written first and then the variable is included in parentheses and sometimes you write the variable name followed by a dot and the method name. How do I know when to do the former one and when the latter one?

  • Dhawal Salvi
    Dhawal Salvi Month ago

    Can we concatinate list with string.. in print()?

  • Filip Kuvacic
    Filip Kuvacic Month ago +1

    I love you.

  • Mr. Carnage
    Mr. Carnage Month ago

    Which python IDE is he using for coding?

    • Corey Schafer
      Corey Schafer  Month ago

      Hey There. I use Sublime Text for my tutorials since it's pretty minimalist. I also use VSCode for my day-to-day coding. I made a video on how I set up my Python development environment in both of those editors. You can find those videos here:
      Sublime Text - thexvid.com/video/xFciV6Ew5r4/video.html
      VSCode - thexvid.com/video/06I63_p-2A4/video.html
      Thanks!

  • HYPER LIGHT
    HYPER LIGHT 2 months ago +2

    Thanks , realy helpfull

  • pc722800
    pc722800 2 months ago

    what is the name of the plugin used to comment multiple lines at a time?

  • Khalil Carlosse
    Khalil Carlosse 2 months ago +3

    Ah yes my favorite subject: Education

  • stayangrystayfoolish
    stayangrystayfoolish 2 months ago

    May I ask very baby question? Do I have to remember all command to have a job as a programmer?

  • ravjot singh
    ravjot singh 2 months ago

    #convert the positive list into negative with user input
    a = input("enter the list").split(",")
    print(a)
    print(type(a))
    def negative(b):
    neg = []
    for i in b:
    neg.append(-i)
    return neg
    print(negative(a))




    I am getting an error.
    Traceback (most recent call last):
    File "first.py", line 9, in
    print(negative(a))
    File "first.py", line 7, in negative
    neg.append(-i)
    TypeError: bad operand type for unary -: 'str'

  • Kevin Ha
    Kevin Ha 2 months ago +1

    The best tutorial for Python !!! Great job !!!

  • dinushka piyumal
    dinushka piyumal 2 months ago

    nodakin

  • pravin kalake
    pravin kalake 2 months ago

    @Corey Schafer just a Quick Question. How do you comment and uncomment multiple line of codes?

  • Alex Sage
    Alex Sage 2 months ago

    Let's say I use single ' instead of " but in a list I have 'What's up!' (which has that character in it) how can I make it so that ' character won't counteract? replace it with something?

  • Igor Nikachin
    Igor Nikachin 2 months ago +1

    Corey, i fucking love. YOU ARE THE MAN!!!!

  • Alex Sage
    Alex Sage 2 months ago +1

    great tut!

  • Mickey Kr
    Mickey Kr 2 months ago

    Hey sir, My question is what is the role of empty list,tuple or set?

  • Jing Liu
    Jing Liu 2 months ago +2

    I love all your Python courses!!! You are the best!!! I feel so lucky to know you on TheXvid and you get many of my Python issues clear. THANK YOU!!!

  • Louis Balderas
    Louis Balderas 2 months ago +2

    Quick question, what hotkeys are you using to uncomment and comment a block of lines?

  • BARKAT ALI
    BARKAT ALI 2 months ago

    courses = 'hisory','chemisry','biology','maths','science'
    courses.append('art')
    print(courses)
    I am getting following error
    Traceback (most recent call last):
    File "/Users/rejiismail/Documents/Python/test1.py", line 2, in
    courses.append('art')
    AttributeError: 'tuple' object has no attribute 'append'

    • BARKAT ALI
      BARKAT ALI 2 months ago

      Sorry got it I was not using square bracket at the start of courses.

  • Dennis Will
    Dennis Will 2 months ago +1

    Great overview of the differences between lists and tuples!

  • Jerry Brice
    Jerry Brice 2 months ago +1

    Superb delivery. Thank you!

  • mike Princivil
    mike Princivil 3 months ago

    how did he comment out multiple lines like that?

    • zzz000zz
      zzz000zz 3 months ago

      From the Sublime Text Editor, select Edit > Comment (or "command+/" on a Mac.) You can also un-comment multiple lines but I will let you learn that on your own.

  • Hardik Goel
    Hardik Goel 3 months ago +1

    4 lessons in I love it

  • Ankur Kumar
    Ankur Kumar 3 months ago +1

    A valuable note:
    *join()* method works on a list of strings. It won't work on a list of integers.

    • rodwynnejones
      rodwynnejones Month ago +1

      @Ankur Kumar I did comment that your comment is correct...It just got me thinking..."is there a way to do it".

    • Ankur Kumar
      Ankur Kumar Month ago

      @rodwynnejones I admire your response, but didn't you just use map( ) to pass an iterable(list) to a function str( ) which in returns create an iterator and then converted it back to a list of strings. As, I said above on my comment, it's practically the same. The way of doing it different but at core .join method works only on list of string items as you can also see. O:)

    • rodwynnejones
      rodwynnejones Month ago

      True, but you can work around it:-
      mylist = [1, 2, 3, 4, 5, 6, 7]
      mylist2 = list(map(str, mylist))
      print(int(''.join(mylist2)))

  • That One User
    That One User 3 months ago +3

    1:00 - Lists
    22:03 - Tuples
    23:35 - Sets

  • nyes liberty
    nyes liberty 3 months ago +1

    absolute geginner but im telling you am getting along with every thing here ... thanks man for the great work im really in class while at home.

  • Yogi Peram
    Yogi Peram 3 months ago +1

    Very useful content.. Thank you

  • ravi chandra
    ravi chandra 4 months ago

    Why does the reverse method on sorted(list) version prints None. s = sorted(existing_list) , print(s.reverse()) //prints None

  • Mohammed Amer
    Mohammed Amer 4 months ago +1

    Thank You So Much!

  • Nitesh Bagla
    Nitesh Bagla 4 months ago +1

    What's the use of creating an empty tuple?

  • Tom
    Tom 4 months ago

    which program are u running your code on?

    • Corey Schafer
      Corey Schafer  4 months ago

      Hey There. I use Sublime Text for my tutorials since it's pretty minimalist. I also use VSCode for my day-to-day coding. I made a video on how I set up my Python development environment in both of those editors. You can find those videos here:
      Sublime Text - thexvid.com/video/xFciV6Ew5r4/video.html
      VSCode - thexvid.com/video/06I63_p-2A4/video.html
      Thanks!

  • nikhil t
    nikhil t 4 months ago

    del courses[0]
    only legends know this

  • Reza Sadr
    Reza Sadr 4 months ago

    Hi ! I'm enjoying learning with your videos, a question:
    at 16':45'' (the time in the video time), how we can change two identical words at the same time? (here 2'item' change to 'course' at the same time.

    • Issac Wiggins
      Issac Wiggins 3 months ago

      I know in some editors you can hold CTRL and click on different areas of the text editors and it allows you edit/write over whatever was there previously.

  • Cheerful Channel
    Cheerful Channel 4 months ago +1

    Thanks for the tutorials! it's inspiring me

  • Lelre Ferreira da Silva

    How can I receive informations from the keyboard and save it in a list using for-loop?

  • Esraa Mohamed
    Esraa Mohamed 4 months ago +1

    Thank you for your hard work