How to Use Lists in Python Notes
I am going to be detailing out my notes & examples of Python Lists from my Udemy Python Bootcamp.
Lists
- Ordered sequences that can hold a variety of object types
- Lists support indexing and slicing
- Lists are flexible by holding multiple data types i.e
- my_list =[1,’test’,5,10.2,’Space’]
- Lists also work with indexing
- my_list[1] will return “test”
- You can also concatenate lists
- You can mutate lists which is a difference from strings
- Lists Example:
- indian_schools = [“Zinc School”, “DAV Public School”, “St. Gregorious”]
- us_schools = [“Davidson Middle School”,”Anderson High”]
- Concatenating Lists
- my_schools = indian_schools + us_schools
- my_schools
- >> [‘Zinc School’, ‘DAV Public School’, ‘St. Gregorious’, ‘Davidson Middle School’, ‘Anderson High’]
- Show Item at 0 location
- my_schools[0] = “Zinc Sr. Secondary Schools”
- Adding to a List
- You can add to a list by using append() method
- my_schools.append(“Wayne State University”)
- my_schools
- >> [‘Zinc Sr. Secondary Schools’,’DAV Public School’,’St. Gregorious’, ‘Davidson Middle School’, ‘Anderson High’, ‘Wayne State University’]
- Removing an Item
- You can use .pop() method to remove an item from the end of the list if you don’t specify an index value
- Example:
- [‘Zinc Sr. Secondary Schools’,’DAV Public School’,’St. Gregorious’, ‘Davidson Middle School’, ‘Anderson High’]
- .pop() shows the item that was removed from the end of the list, so you can use the popped item elsewhere if you wanted to
- .pop(2) will remove an item that is at 2 index value from the list
- Sort Method
- Sorts the list in place which means you cannot re-assign the sort to another variable
- i.e. You cannot do
- My_sorted_list = new_list.sort()
- You need to do
- new_list.sort()
- My_sorted_list = new_list
You can review my Learning to Code in Python article to see how I got started coding in Python. I am currently working on a few projects that would further advance my Python skills, including building a used-car platform leveraging Scrapy. I am still in early stages, but the goal is to provide insights on used cars, specifically identifying cars that are considered a good+ deal depending on how much the vehicles of the same make/model and price are being sold in the region. Will share the link to the platform once it is out. I am hoping that platform would serve as a significant advancement to my data-science and my python development skills.