
Lists
Python Lists are ordered collections of items, where each item can be of any data type, and they are enclosed within square brackets []. Lists support various operations such as appending, indexing, slicing, and iterating. They can contain heterogeneous data types, allowing flexibility in storing different kinds of elements like integers, strings, floats, or even other lists (nested lists). In addition, they are mutable, meaning their elements can be changed after creation, making them versatile for dynamic data storage and manipulation. Furthermore, they support indexing and slicing to access elements or sublists; and have their own methods, which we will see below.
Dataset:
basketball_champions= [
'Los Angeles Lakers', 17,
'Boston Celtics', 17,
'Golden State Warriors', 7,
'Chicago Bulls', 6,
'San Antonio Spurs', 5,
'Philadelphia 76ers', 3,
'Detroit Pistons', 3,
'Miami Heat', 3,
'New York Knicks', 2,
'Houston Rockets', 2,
'Milwaukee Bucks', 2,
'Cleveland Cavaliers', 1,
'Atlanta Hawks', 1,
'Washington Wizards', 1,
'Oklahoma City Thunder', 1,
'Portland Trail Blazers', 1,
'Dallas Mavericks', 1,
'Sacramento Kings', 1,
'Toronto Raptors', 1,
'Denver Nuggets', 1
]1. Subsetting Lists
1.1. Single Element
1.2. Multiple Elements (Slicing)
2. Updating Lists
2.1. Changing list elements
2.2. Adding and removing elements
3. List Methods
Adds an element at the end of the list
Removes all the elements from the list
Returns a copy of the list
Returns the number of elements with the specified value
Add the elements of a list (or any iterable), to the end of the current list
Returns the index of the first element with the specified value
Adds an element at the specified position
Removes the element at the specified position
Removes the first item with the specified value
Reverses the order of the list
Sorts the list
Click on the methods practice them on W3schools
Lists are great data types to store data; however, they fall short when it comes to arithmetic:
To do such calculation we need the help of a for loop:
A better approach would be to use the Numpy package! We first convert our list to a numpy array and then can do the multiplication without having use of a for loop.
Conclusion
Python lists are versatile data structures that can hold a collection of elements of different types. They are mutable, meaning we can modify their contents after creation. Lists support indexing and slicing to access elements or sublists and have built-in methods to operate on them more easily. They are dynamic in size and can grow or shrink as needed, making them a fundamental building block for many Python programs.
All being said, because of the nature of the dataset we used (i.e. having only pairs of 'team' and 'championships') it is better if we use another Python's data structure called Dictionary.
Last updated
Was this helpful?