Python создать лист заданного размера

Создайте пустой список определенного размера в Python

В этом посте мы обсудим, как создать пустой список заданного размера в Python.

Чтобы присвоить любое значение списку, используя оператор присваивания в позиции i , a[i] = x , размер списка должен быть не менее i+1 . В противном случае он поднимет IndexError , как показано ниже:

Решение состоит в том, чтобы создать пустой список None когда элементы списка заранее неизвестны. Это можно легко сделать, как показано ниже:

Приведенный выше код создаст список размеров 5 , где каждая позиция инициализируется None . None часто используется в Python для обозначения отсутствия значения.

Другой альтернативой для создания пустых списков заданного размера является использование генераторов списков:

Какое решение использовать?

Первое решение хорошо работает для нессылочных типов, таких как числа. Но в некоторых случаях вы можете столкнуться с ошибками ссылок. Например, [[]] * 5 приведет к повторению списка, содержащего один и тот же объект списка 5 раз.

Решение этой проблемы заключается в использовании списков, подобных этому:

Это все о создании пустого списка заданного размера в Python.

Средний рейтинг 4.9 /5. Подсчет голосов: 20

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

How to Create a Python List of Size n?

Be on the Right Side of Change

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] .

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:

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:

Читайте также:  Java operator cannot be applied to java lang string

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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.

Читайте также:  Целочисленный тип данных питон

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

Initialize a list with given size and values in Python

This article explains how to initialize a list with any size (number of elements) and values in Python.

See the following article about the initialization of NumPy array ndarray .

Create an empty list

An empty list is created as follows. You can get the number of elements in a list with the built-in len() function.

l_empty = [] print(l_empty) # [] print(len(l_empty)) # 0 

You can add an element using the append() method and remove it using the remove() method.

l_empty.append(100) l_empty.append(200) print(l_empty) # [100, 200] l_empty.remove(100) print(l_empty) # [200] 

See the following articles for details on adding and removing elements from a list.

Initialize a list with any size and values

As mentioned above, in Python, you can easily add and remove elements from a list. Therefore, in most cases, it is not necessary to initialize the list in advance.

If you want to initialize a list with a specific size where all elements have the same value, you can use the * operator as shown below.

l = [0] * 10 print(l) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print(len(l)) # 10 

A new list is created by repeating the elements of the original list for the specified number of times.

print([0, 1, 2] * 3) # [0, 1, 2, 0, 1, 2, 0, 1, 2] 

You can generate a list of sequential numbers with range() .

Notes on initializing a 2D list (list of lists)

Be cautious when initializing a list of lists.

Avoid using the following code:

l_2d_ng = [[0] * 4] * 3 print(l_2d_ng) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

With this code, updating one list will change all the lists.

l_2d_ng[0][0] = 5 print(l_2d_ng) # [[5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0]] l_2d_ng[0].append(100) print(l_2d_ng) # [[5, 0, 0, 0, 100], [5, 0, 0, 0, 100], [5, 0, 0, 0, 100]] 

This issue occurs because all the inner lists reference the same object.

print(id(l_2d_ng[0]) == id(l_2d_ng[1]) == id(l_2d_ng[2])) # True 

Instead, you can use list comprehensions as demonstrated below.

l_2d_ok = [[0] * 4 for i in range(3)] print(l_2d_ok) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

Each inner list is treated as a separate object.

l_2d_ok[0][0] = 100 print(l_2d_ok) # [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] print(id(l_2d_ok[0]) == id(l_2d_ok[1]) == id(l_2d_ok[2])) # False 

Although range() is used in the above example, any iterable with the desired number of elements is acceptable.

l_2d_ok_2 = [[0] * 4 for i in [1] * 3] print(l_2d_ok_2) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] l_2d_ok_2[0][0] = 100 print(l_2d_ok_2) # [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] print(id(l_2d_ok_2[0]) == id(l_2d_ok_2[1]) == id(l_2d_ok_2[2])) # False 

If you want to create a multidimensional list, you can use nested list comprehensions.

l_3d = [[[0] * 2 for i in range(3)] for j in range(4)] print(l_3d) # [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]] l_3d[0][0][0] = 100 print(l_3d) # [[[100, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]] 

Initialize a tuple and an array

You can also initialize tuples as well as lists.

Читайте также:  Python цикл по дате

Note that a single-element tuple requires a comma , to differentiate it from a regular value.

t = (0,) * 5 print(t) # (0, 0, 0, 0, 0) 

For the array type, you can pass the initialized list to its constructor.

import array a = array.array('i', [0] * 5) print(a) # array('i', [0, 0, 0, 0, 0]) 

See the following article for the difference between list and array .

  • Convert list and tuple to each other in Python
  • Unpack and pass list, tuple, dict to function arguments in Python
  • Convert numpy.ndarray and list to each other
  • GROUP BY in Python (itertools.groupby)
  • Get the number of items of a list in Python
  • Sort a list, string, tuple in Python (sort, sorted)
  • Swap values ​​in a list or values of variables in Python
  • Reverse a list, string, tuple in Python (reverse, reversed)
  • Convert a list of strings and a list of numbers to each other in Python
  • Transpose 2D list in Python (swap rows and columns)
  • Remove an item from a list in Python (clear, pop, remove, del)
  • Pretty-print with pprint in Python
  • zip() in Python: Get elements from multiple lists
  • Extract, replace, convert elements of a list in Python
  • Extract specific key values from a list of dictionaries in Python

Источник

Оцените статью