Python is a very user-friendly yet powerful programming language, which is why it is used so prolifically in data science for data analysis and building machine learning algorithms, in deep learning to build neural network models, and even in software development for developing applications in python functions list or Python – List Methods.
One of Python’s unique points is that it supports various kinds of data structures like lists, tuples, dictionaries, etc., which in turn come with a plethora of in-built methods making solving programming challenges with Python extremely easy. But unfortunately, newcomers and even veteran Python programmers aren’t aware of all of these methods.
I am going to pick one of these data structures, Python lists, and focus on all the must-know methods and functions that come in handy when solving problems with lists. So, by the end of this article, whether you are a data scientist or a hard-core programmer, you will come out armed with a solid knowledge of Python lists which will make your next task in Python much easier.
This article was published as a part of the Data Science Blogathon.
Python lists are the primary and certainly the foremost common container.
In Python, a Function may be passed input parameters and may or may not return a result. Method, on the other hand, maybe passed off as an object instance and may or may not result in the expected output. The key difference between the two is that Functions may take objects as inputs while Methods, in contrast, act on objects. So, while all methods are functions in the Python programming language, not all functions are methods.
Also Read- Python Interview Questions to Ace Your Next Job Interview in 2024
Before we look at the functions and methods for Python lists, let’s first see how to create a list in Python.
The list() function allows us to create a list in Python. It takes an iterable as a parameter and returns a list. This iterable can be a tuple, a dictionary, a string, or even another list.
# sample iterables
sample_tuple = (1,2,3,4)
sample_dict = {'a': 1, 'b': 2, 'c': 3}
sample_string = 'hello'
# converting to list
print('tuple to list', list(sample_tuple))
print('dict to list', list(sample_dict))
print('string to list', list(sample_string))
Here is how the output would look like:
[1,2,3,4]
['a', 'b', 'c', 'd']
['h', 'e', 'l', 'l', 'o']
Now let’s see all the functions and methods supported by Python lists, one by one, with the help of examples.
The sort() method is a built-in Python method that, by default, sorts the list in ascending order. However, you’ll modify the order from ascending to descending by specifying the sorting criteria.
Example
Let’s say you would like to sort the elements of the product’s prices in ascending order. You’d type prices followed by a . (period) followed by the method name, i.e., sort, including the parentheses. Check out the syntax for it in the following lines of code –
Python Code:
#You can try the codes here
prices = [589.36, 237.81, 230.87, 463.98, 453.42]
prices.sort()
print(prices)
For the type() function, it returns the class type of an object.
Example
In this example, we will see the data type of the formed container.
fam = ["abs", 1.57, "egfrma", 1.768, "mom", 1.71, "dad"]
type(fam)
Output:
list
The append() method will add some elements you enter to the end of the elements you specified.
Example
In this example, let’s increase the length of the string by adding the element “April” to the list. Therefore, the append() function will increase the length of the list by 1.
months = ['January', 'February', 'March']
months.append('April')
print(months)
Output:
['January', 'February', 'March', 'April']
We can iterate over each element in the list using a for-loop –
for element in months:
print(element)
Output:
January
February
March
April
The extend() method increases the length of the list by the number of elements that are provided to the strategy, so if you’d prefer to add multiple elements to the list, you will be able to use this method.
Example
In this example, we extend our initial list having three objects to a list having six objects.
list = [1, 2, 3]
list.extend([4, 5, 6])
list
Output:
[1, 2, 3, 4, 5, 6]
The index() method returns the primary appearance of the required value.
Example
In the below example, let’s examine the index of February within the list of months.
months = ['January', 'February', 'March', 'April', 'May']
months.index('March')
Output:
2
The max() function is a built-in function in Python that returns the largest value from the values that are input.
Example
In this example, we’ll look to use the max() function for hunting out the foremost price within the list-named price.
prices = [589.36, 237.81, 230.87, 463.98, 453.42]
price_max = max(prices)
print(price_max)
Output:
589.36
The min() function is another in-built Python function that returns the rock bottom value from the input values.
Python list methods with examples
In this Example, you will find the month with the tiniest consumer indicator (CPI).
To identify the month with the tiniest consumer index, you initially apply the min() function on prices to identify the min_price. Next, you’ll use the index method to look out for the index location of the min_price. Using this indexed location on months, you’ll identify the month with the smallest consumer indicator.
months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
# Identify min price
min_price = min(prices)
# Identify min price index
min_index = prices.index(min_price)
# Identify the month with min price
min_month = months[min_index]
print[min_month]
Output:
February
The len() function takes the list as input and returns the number of elements in a specified list.
Example
In the below example, we are going to take a look at the length of the 2 lists using this function.
list_1 = [50.29]
list_2 = [76.14, 89.64, 167.28]
print('list_1 length is ', len(list_1))
print('list_2 length is ', len(list_2))
Output:
list_1 length is 1
list_2 length is 3
The clear() method removes all the elements from a specified list and converts them to an empty list.
Example
In this example, we’ll remove all the elements from the month’s list and make it empty.
months = ['January', 'February', 'March', 'April', 'May']
months.clear()
Output:
[ ]
The insert() method inserts the required value at the desired position.
Example
In this example, we’ll Insert the fruit “pineapple” at the third position of the fruit list.
fruits = ['apple', 'banana', 'cherry']
fruits.insert(2, "pineapple")
Output:
['apple', 'banana', 'pineapple', 'cherry']
The count() method returns the number of elements with the desired value.
Example
In this example, we are going to return the number of times the fruit “cherry” appears within the list of fruits.
fruits = ['cherry', 'apple', 'cherry', 'banana', 'cherry']
x = fruits.count("cherry")
Output:
3
The pop() method removes the element at the required position.
Example
In this example, we are going to remove the element that’s on the third location of the fruit list.
fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']
fruits.pop(2)
Output:
['apple', 'banana', 'orange', 'pineapple']
The remove() method removes the first occurrence of the element with the specified value.
Example
In this example, we will Remove the “banana” element from the list of fruits.
fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']
fruits.remove("banana")
Output:
['apple', 'cherry', 'orange', 'pineapple']
The reverse() method reverses the order of the elements.
Example
In this example, we will reverse the order of the fruit list so that the first element in the initial list becomes last and vice-versa in the new list.
fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']
fruits.reverse()
Output:
['pineapple', 'orange', 'cherry', 'banana', 'apple']
The copy() method returns a copy of the specified list and makes a new list.
Example
In this example, we want to create a list having the same elements as the list of fruits.
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
Output:
['apple', 'banana', 'cherry', 'orange']
With the filter() function in Python, we can provide an iterable and the condition on which we want to filter out the data in the iterable. The filter() function then returns an iterator of filtered elements.
Let’s take a sample dataset in a list and filter out elements from it. Say, we take numbers from 1 to 10 and filter out even numbers from the list.
Let’s first define a function that filters out the elements.
def filter_func(num):
if num%2==0:
return num
else:
return
Now, let’s use the filter() function to filter out the elements from the list.
filtered_output = filter(filter_func, [1,2,3,4,5,6,7,8,9,10])
Let’s put the filtered output in a list and print it.
list(filtered_output)
Here is the output that you will get.
[2, 4, 6, 8, 10]
So in this article, we got acquainted with the various functions and Python Lists methods. We covered the basics and looked at the implementation of the most important functions and methods. These come in handy whether you are doing analysis on datasets as Data Analyst or whether you are building machine learning models as a Data Scientist.
Key Takeaways
If you found this article useful, I encourage you to read the following related articles on Analytics Vidhya’s blog:
A. In Python, a list is a built-in data structure that allows you to store an ordered collection of items. Python provides various methods to manipulate and work with lists, such as append()
to add an item to the end, insert()
to insert an item at a specified index, remove()
to remove an item, pop()
to remove and return an item, index()
to get the index of an item, count()
to count occurrences of an item, sort()
to sort the list, reverse()
to reverse the order, and extend()
to add multiple items.
A. To list all available methods for a particular object or data type in Python, you can use the dir()
function. For example, print(dir(list))
will print a list of all attributes and methods associated with the list
data type.
A. Python methods are functions that are associated with specific objects or classes. They are defined within the class and can operate on the object’s data (attributes) or perform operations related to that object. Methods are called on an instance of a class using dot notation, like object.method()
. Python provides many built-in methods for various data types and classes, and you can also define your own custom methods.
A. In Python, list[:]
is a slicing operation that creates a shallow copy of the entire list. It returns a new list containing all the elements of the original list, which is a common way to create a copy without modifying the original. For example, new_list = original_list[:]
creates new_list
as a separate list instance with the same elements as original_list
.
The list() function in Python helps you make a list. You can use it to turn other things, like numbers or words, into a list. It’s like putting items in a basket so you can easily work with them.
The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.
Thanks for this overview! Please check code sample for insert() function. Seems that it was not updated according to the text.
The reverse function doesn't always work in the intended way. For example if you just wanna print the reversed string it'll work just like you did above. But if you want to assign the reversed string to a new variable for later use, it will render it Un-iteratable by changing its data type.
Thanks. Above article is very much interested specially for non computer beginners. It is presented in simple words.