18 Most Common Python List Questions
Originally posted on https://www.datacamp.com/community/tutorials/18-most-common-python-list-questions-learn-python
Python lists are an increasingly popular topic for those who are starting to learn the language as well as for those who are already experienced with it.
With this post, we tackle this one topic. We will list 18 most frequently asked questions about Python lists, so that you can understand -and avoid- these doubts.
If you want to get familiar with programming in Python instead, you should take a look at DataCamp’s Intro to Python for Data Science course. If, however, you’re already acquainted with Python and already have some experience, you might be interested in DataCamp’s Intermediate Python for Data Science course.
(PS. The original post includes code chunks that allow you to try out the answers to the questions listed below!)
1. When Should I Use Lists And When Tuples, Dictionaries Or Sets?
The Python list structure seems pretty straightforward when you’re just reading it, but when you’re actually working on a small Python script or a whole project, the choice for a list or some other sequence type might not be as clear to you.
However, choosing the right data structure for your data is essential! Below we list some of the differences between lists and other data types such as tuples, dictionaries, and sets.
Python Lists Versus Tuples
If you’re defining a constant set of values and all you’re going to do with it is iterate through it, use a tuple instead of a list. It will be faster than working with lists and also safer, as the tuples contain “write-protect” data.
Python Lists Versus Dictionaries
Use a dictionary when you have an unordered set of unique keys that map to values. Note that, because you have keys and values that link to each other, the performance will be better than lists in cases where you’re checking membership of an element.
Python Lists Versus Sets
You should make use of sets when you have an unordered set of unique, immutable values that are hashable.
2. How Can You Select An Element From A List?
If you want who work properly with lists in Python, you will need to know how to access them. You typically access lists to change certain values, to update or delete them, or to perform some other kind of operation on them. The way you access lists, and, by extension, all other sequence types, is by using the index operator [ ]. Inside, you put an integer value.
3. How Do I Transform Lists into Other Data Structures?
Sometimes, a list is not exactly what you need to continue. In these cases, you might want to know how to transform your list to a more appropriate data structure. Below, we list some of the most common transformation questions and their answers.
How To Convert A Python List To A String
You convert a list to a string by using ''.join(). This operation allows you to glue together all strings in your list together and return them as a string. Note, however, that if your list only contains integers, you should convert the elements to strings before performing the join method on them.
How to Convert A Python List to a Tuple
You can change a list to a tuple in Python by using tuple(). Pass your list to this function and you will get a tuple back! But make sure you remember that tuples are immutable. You can’t change them afterwards!
How to Convert Your Python List to a Set
As you will remember, a set is an unordered collection of unique items. That means not only means that any duplicates that you might have had in your original list will be lost once you convert it to a set, but also the order of the list elements. You can change a list into a set with the set() function. Just pass your list to it!
How to Convert Python Lists to Dictionaries
A dictionary works with keys and values, so the conversion from a list to a dictionary might seem less straightforward. You will need to make sure that the list elements are interpreted as key-value pairs. The way to do this is to select them with the slice notation and pass them to zip().
4. How Can I Determine The Size Of My List?
You can pass your list to the len() function to get the size of your Python list back. Note that the len() function is not specifically for lists, but you can also use it with other sequences or collections, such as dictionaries, sets, strings, etc.
5. What’s The Difference Between The append() and extend() Methods?
The extend() method, on the one hand, takes an iterable (that’s right, it takes a list, set, tuple or string!), and adds each element of the iterable to the list one at a time.
The append() method, on the other hand, adds its argument to the end of the list as a single item, which means that when the append() function takes an iterable as its argument, it will treat it as a single object.
Make sure to read the original article if you want to test this out for yourself!
Remember that we say that a certain value is iterable when your program can iterate over it. In other words, an iterable is a value that represents a sequence of one more values. As you probably read in the first section, lists are sequences and all instances of Python’s sequence types are iterables.
6. How Do I Concatenate Lists?
To concatenate lists, you use the + operator. It will give you a new list that is the concatenation of your two lists without modifying the original ones.
The concatenating and appending operations might be confusing! The append() method is different from the + operator, which in its turn is very similar to the extend() method, but not exactly the same… You see that with append() and extend(), you modify your original list, while with the + operator, you can make another list variable.
7. How Can I Sort a List?
There are two very simple ways to get the values in your Python lists sorted in ascending or descending order: you use the sort() method of Python lists or you use the sorted() function and pass a list to it. You can apply the sorted() function to any Iterable object, which means that it also accepts strings, sets, dictionaries when they are passed to it!
Note that your original list is changed after you have performed the sorting to it. It is advised to use this in cases where you have no use for your original list anymore.
8. How To Clone Or Copy a List
There are a lot of ways of cloning or copying a Python list: firstly, you can slice your original list and store it into a new variable. Secondly, you can use the built-in list() function. Thirdly, you can use the copy library with the copy() method. If your list contains objects and you want to copy those as well, you can use copy.deepcopy().
9. How Does List Comprehension Work?
List comprehension is, basically speaking, a way of elegantly constructing your Python lists. The best thing about this (for those who love math) is the fact that they look a lot like mathematical lists.
Are you curious to see examples of this? Read more here.
In in a more general sense, you can also use list comprehension to transform your lists into other lists, which sounds a bit more difficult, doesn’t it?
Note that besides list comprehensions, also set and dictionary comprehensions exist.
In short, this has just been a short introduction to list comprehension; There is much more to discover about it. Keep on reading to learn more about nested list comprehension and to see more practical examples of what list comprehension can mean for your programming with Python!
10. How Do I Count Occurrences of a List Item?
Since lists don’t have the item uniqueness criterion, like sets, you might want to know more about how not only many times one particular list item occurs in your list but also how many times each list item is encountered.
Counting the occurrences of one list item. To count the occurrences of just one list item you can use the count() method.
Counting all list items. To count the occurrences of items in a list, you can also use list comprehension in combination with the count() method.
Counting all Python list items with Counter(). Alternatively, there’s the faster Counter() method from the collections library.
11. How Do I Split a List into Evenly Sized Chunks?
To split your list up into parts of the same size, you can resort to the zip() function in combination with iter().
12. How Do I Loop over a List?
You can easily loop through any list with a for loop. For those of you who haven’t worked much with for loops, it works as follows: the for loop allows you to perform an action for every element in your list. How you construct the for loop is more elaborately explained here.
13. How Do I Create Flat Lists Out Of Lists?
To make a simple list out of a list of lists, you can use the sum() function. Just don’t forget to pass your list and an empty list to it.
You can also use a two different approaches to flatten your lists: you either use the reduce() method, to which you pass a lambda function. Now, the reduce() method is there to ensure that your iterable is reduced to a single value. How the iterable is reduced is determined by the function that you pass to it.
The second option to make flat lists out of lists of lists is to use list comprehension.
14. How Do I Get an Intersection Of Two Lists?
List Intersection Using List Comprehension
If you want to obtain the intersection of two lists, you can use the filter() function. Note that, since filter() returns an iterable instead of a list, you need to wrap all you put into your filter() with list(). For better readability, however, you could also work with nested list comprehensions. For examples, go to the original article.
Intersecting Lists With set()
If the order of your elements is not important and if you don’t need to worry about duplicates then you can use set intersection.
15. How Do I Remove Duplicates From a List?
As described in the first section of this post, it’s best to select a set if you want to store a unique collection of unordered items.
To create a set from any iterable, you can simply pass it to the built-in set() function. If you later need a real list again, you can similarly pass the set to the list() function.
16. Why NumPy Arrays Instead Of Lists?
In general, there seem to be four reasons why Python programmers prefer NumPy arrays over Python lists:
- because NumPy arrays are more compact than Python lists,
- because access in reading and writing items is faster with NumPy,
- because NumPy can be more convenient to work with, thanks to the fact that you get a lot of vector and matrix operations for free, and
- because NumPy can be more efficient to work with because they are implemented more efficiently.
17. How Do I Create Empty NumPy Arrays?
If you just want to create an empty NumPy array, you can just do this: numpy.array([]). However, if your goal is to initialize a NumPy array, you can also use the zeros(), ones() and empty() methods from the NumPy library.
Remember that you can check out the original article if you want to see the code examples!
18. How Do I Do Math With Lists?
A lot of the time, we not only use lists to store a collection of values, but we also use it to perform some mathematical operations on it. This section will cover some of the most frequently asked questions on doing math with Python lists.
How Do I Calculate the Weighted Average of a Python List?
The weighted average is much like an average but is slightly different: a weighted average returns a number that depends on the variables of both value and weight.
You can easily calculate the weighted average with a for loop or list comprehension.
How Do I Calculate the Quantile of a Python List?
Quantiles are essential to making a summary of your data set, next to the minimum and maximum of your set. You also have the 25th, 50th, and the 75th percentile, but they are also called first quartile, median and third quartile.
The easiest way to do this is by working with NumPy. The percentile() method will prove to be a good solution for you!
How Do I Sum Python Lists Element-Wise With Basic Python?
You can use map with operator.add to perform an element-wise addition. Or you can use the zip() function with a list comprehension.
How Do I Sum Python Lists Element-Wise With NumPy?
The previous examples worked perfectly on these small lists, but when you’re working with slightly more data, you should probably use the NumPy library to make the process easier.
You should then make sure that you import the NumPy library and that your lists are converted into NumPy arrays.
What’s Up Next In Your Data Science Journey With Python?
You have reached the end of our list of the most popular Python list questions. You made it!
Python lists are only a small but essential element in your data science journey. Are you ready to go even further?
You might be interested in our Importing Data Into Python course or consider reading our The importance of preprocessing in data science and the machine learning pipeline tutorial series!
Lets connect here on Linkedin. I saw your great work on Python/ML/Data Visualization and Scikit-learn Cheat Sheets or how to develop and implement/validate model (Machine Learning Algorithms:Supervised Learning.Great Learning indeed.