Hướng dẫn python list capacity

To create a list of n placeholder elements, multiply the list of a single placeholder element with n. For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None. You can then overwrite some elements with index assignments. In the example, lst[2] = 42 would result in the changed list [None, None, 42, None, None].

Nội dung chính

  • Where to Go From Here?
  • What are Lists in Python?
  • How to Get the Size of a List in Python?
  • 1] Len[] method
  • 2] Naïve method
  • 3] length_hint[] method
  • Video liên quan

Let’s play with an interactive code shell before you’ll dive into the detailed solution!

Exercise: Initialize the list with n=20 placeholder elements -1 and run the code.

Next, you’ll learn about the more formal problem and dive into the step-by-step solution.

Problem: Given an integer n. How to initialize a list with n placeholder elements?

# n=0 --> [] # n=1 --> [None] # n=5 --> [None, None, None, None, None]

Solution: Use the list concatenation operation *.

n = 5 lst = [None] * n print[lst] # [None, None, None, None, None]

You can modify the element n as you like. In subsequent operations, you can overwrite all placeholder None list elements using simple index assignment operations:

lst[0] = 'Alice' lst[1] = 0 lst[2] = 42 lst[3] = 12 lst[4] = 'hello' print[lst] # ['Alice', 0, 42, 12, 'hello']

However, there’s a small problem if you want to create a list with mutable objects [such as a list of lists]:

lst = [[]] * n print[lst] # [[], [], [], [], []] lst[2].append[42] print[lst] # [[42], [42], [42], [42], [42]]

Changing one list element changes all list elements because all list elements refer to the same list object in memory:

The solution is to use list comprehension [see my detailed blog tutorial on list comprehension for a complete guide]:

lst = [[] for _ in range[n]] print[lst] # [[], [], [], [], []] lst[2].append[42] print[lst] # [[], [], [42], [], []]

In the following visualization, you can see how each element now refers to an independent list object in memory:

Exercise: Run the visualization and convince yourself that only one element is modified! Why is this the case?

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Python is one of the fundamental programming languages widely used in the machine learning and artificial intelligence domain. Python possesses various data structures which help you to deal with data effectively and efficiently. The list is one of the sequential data structures in python that is highly used to store data collection and operate on it. In this article, let us study how to find python list size with 3 methods and examples in detail. But before that, let us have a brief introduction to a list data structure in python below.

What are Lists in Python?

List in python is used to store the multiple elements in a single variable. List elements are ordered, changeable, and also allow duplicate values. Hence, Python lists are mutable, which means that you can modify the elements of the lists after they are created. For initiating the list, you have to insert elements inside the square brackets [[]], each element separated by a comma [,] in between. To learn more about lists, visit our article “3 Ways to Convert Lists to Tuple”.

For example:

sample_list = ['Programming', 'with', 'Favtutor']; print[sample_list]

Output

['Programming', 'with', 'Favtutor']

How to Get the Size of a List in Python?

There are 3 methods by which you can find the size of lists in python. Let us learn all of those methods in detail below:

1] Len[] method

The best way to find the total number of elements in the list is by using the len[] method. The len[] method accepts the lists as an argument and returns the number of elements present. Below is the syntax of the len[] method:

According to programmers, len[] is the most convenient method to get the size of the list in python. The len[] method works in O[1] time as a list is an object and needs memory to store its size.

Check out the below example to understand the working of len[] method in detail:

For example:

sample_list = ['Programming', 'with', 'Favtutor']; list_size = len[sample_list] print[list_size]

Output

Is len[] method specific to list data structure?

No, len[] method is not specifically used to find the size of the list data structure. Programmers also use other data structures like arrays, tuples, and sets while programming in python and often face difficulty finding its length for a different purpose. Therefore, you can use the len[] method to get the size of almost all the data structures or collections, such as dictionaries. Using the len[] method, you can also get the length of a total number of elements inside the set and frozenset.

2] Naïve method

Other than len[] method, you can also loop to find the size of lists in python. In this naïve method, you have to run the loop and increase the counter variable after traversing the element in lists. At last, when the pointer becomes empty, the value stored inside the counter variable is the size of the list. This method is most efficient if you are not available with any other technique. Talking about the basic algorithm, check out the below steps to find the length of the list:

  1. Declare the counter variable and assign zero to it.
  2. Using for loop, traverse the elements of the list, and after every element, increment the counter variable by +1.
  3. Hence, the length of the lists will be stored in the counter variable, and you can return it by representing the counter variable.

For example:

sample_list = ['Programming', 'with', 'Favtutor']; counter = 0 for i in sample_list: counter = counter+1 print[counter]

Output

3] length_hint[] method

Python has an in-built operator named length_hint[] to find the size of the lists. Not only lists, but you can also use this method to find the length of tuples, sets, dictionaries and any other python data structure. The operator.length.hint[] method takes the variable as a parameter in which the data is stored. Note that this is the least used method to find the length of data structure as it is only applicable in python programming. Moreover, you have to import the lenght_hint method from the in-built operator library using the "import" keyword, just like shown in the below example:

For example:

from operator import length_hint sample_list = ['Programming', 'with', 'Favtutor'] list_size = length_hint[sample_list] print[list_size]

Output

Conclusion

Lists in python are a primary data structure, highly used to store the sequential data inside a single variable. At the same time, the information on measuring the size of a list in python is one of the most basic operations that you must know as a programmer. Therefore, we have mentioned the three common methods to find the size of the lists in python with examples and their respective output. It is highly recommended to learn and understand them for making your programming efficient and faster. 

Chủ Đề