Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Create an Empty List in Python?

#1
How to Create an Empty List in Python?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;453870&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<p class="has-global-color-8-background-color has-background">To create an empty list in Python, you can use two ways. First, the empty square bracket notation <code>[]</code> creates a new list object without any element in it. Second, the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list/" data-type="post" data-id="21502" target="_blank">list()</a></code> initializer method without an argument creates an empty list object too.</p>
<p>Both approaches are shown in the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Way 1 to create an empty list:
my_list = [] # Way 2 to create an empty list:
my_list = list()</pre>
<p>Next, you’ll learn many more related Python concepts you need to know that concern creation of lists. Keep reading to keep improving your skills and answer any subsequent question you may have!</p>
<h2>Python list() — Quick Guide</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-23.png" alt="" class="wp-image-453888" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-23.png 1024w, https://blog.finxter.com/wp-content/uplo...00x169.png 300w, https://blog.finxter.com/wp-content/uplo...68x432.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p>Python’s built-in <code>list()</code> function creates and returns a new list object. When used without an argument, it returns an empty list. When used with the optional <code>iterable</code> argument, it initializes the new list with the elements in the iterable.</p>
<p>You can create an empty list by skipping the argument:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> list()
[]</pre>
<p>If you pass an iterable—such as another <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list</a>, a <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank">tuple</a>, a <a rel="noreferrer noopener" href="https://blog.finxter.com/sets-in-python/" target="_blank">set</a>, or a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">dictionary</a>—you obtain a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/" target="_blank">new list object</a> with list elements obtained from the iterable:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> list([1, 2, 3])
[1, 2, 3]</pre>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python list() — A Simple Guide" width="780" height="439" src="https://www.youtube.com/embed/zt19-2eW-hY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Read More</strong>: Read our <a href="https://blog.finxter.com/python-list/" data-type="URL" data-id="https://blog.finxter.com/python-list/" target="_blank" rel="noreferrer noopener">full tutorial on the Finxter blog</a> to learn everything you need to know.</p>
<h2>Python Create Empty List of Size</h2>
<p>To create a list of <code>n</code> placeholder elements, multiply the list of a single placeholder element with <code>n</code>. </p>
<p>For example, use <code>[None] * 5</code> to create a list <code>[None, None, None, None, None]</code> with five elements <code>None</code>. </p>
<p>You can then overwrite some elements with index assignments. </p>
<p>In the example, <code>lst[2] = 42</code> would result in the changed list <code>[None, None, 42, None, None]</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
# Create a list with n placeholder elements
n = 5
lst = [None] * n # Print the "placeholder" list:
print(lst)
# [None, None, None, None, None] # Overwrite the placeholder elements
lst[0] = 'Alice'
lst[1] = 0
lst[2] = 42
lst[3] = 12
lst[4] = 'hello'
print(lst)
# ['Alice', 0, 42, 12, 'hello']</pre>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Create a Python List of Size n?" width="780" height="439" src="https://www.youtube.com/embed/d_uBZeKtXSo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Read More</strong>: Read our <a href="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/" target="_blank" rel="noreferrer noopener">full tutorial on the Finxter blog</a> to learn everything you need to know.</p>
<h2>Python Create Empty List of Lists</h2>
<p>You can create an empty <a href="https://blog.finxter.com/python-list-of-lists/" data-type="post" data-id="7890" target="_blank" rel="noreferrer noopener">list of lists</a> do not use <code>[[]] * n</code> because this creates a nested list that contains the same empty list object n times which can cause problems because if you update one, all inner lists change!</p>
<p class="has-global-color-8-background-color has-background">To create an empty list of lists with n empty inner lists, use the list comprehension statement <code>[[] for _ in range(n)]</code> that creates a fresh empty list object <code>n</code> times.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">n = 5
my_list = [[] for _ in range(n)]
print(my_list)
# [[], [], [], [], []]</pre>
<p>List comprehension is a powerful Python feature and I’ve written a full blog tutorial on it—feel free to watch my general explainer video and read the associated blog article!</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="A Simple Introduction to List Comprehension in Python" width="780" height="439" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Read More</strong>: Read our <a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">full tutorial on the Finxter blog</a> to learn everything you need to know.</p>
<h2>Python Create Empty List and Append in Loop</h2>
<p>Follow these three easy steps to create an <a href="https://blog.finxter.com/how-to-check-if-a-python-list-is-empty/" data-type="post" data-id="9090" target="_blank" rel="noreferrer noopener">empty list</a> and append values to it in a <code>for</code> loop:</p>
<ol class="has-global-color-8-background-color has-background">
<li><code><strong>my_list = []</strong></code> creates the empty list and assigns it to the name <code>my_list</code>.</li>
<li><code><strong>for i in range(10):</strong></code> initializes the for loop to be repeated 10 times using loop variable <code>i</code> that takes on all values between 0, 1, …, 9.</li>
<li><code><strong>my_list.append(i)</strong></code> is the loop body that appends the integer value of the loop variable <code>i</code> to the list.</li>
</ol>
<p>Here’s the code example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = []
for i in range(10): my_list.append(i) print(my_list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
<p>However, a better <a rel="noreferrer noopener" href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank">Python one-liner</a> alternative is using list comprehension for this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [i for i in range(10)]</pre>
<h2>Python Create List of Empty Strings</h2>
<p class="has-global-color-8-background-color has-background">To create a list of <code>n</code> empty strings, you can use the expression <code>[''] * n</code> because it places the same empty string literal <code>''</code> into the list <code>n</code> times. This doesn’t cause any problems due to the fact that all list elements refer to the same empty string object because strings are <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">immutable</a> and cannot be modified anyways.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> [''] * 5
['', '', '', '', '']
>>> [''] * 20
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
</pre>
<h2>Python Create Empty List of Dictionaries</h2>
<p class="has-global-color-8-background-color has-background">To create a list of <code>n</code> dictionaries, each <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank">dict</a> being empty, use the <a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">list comprehension</a> statement <code>[dict() for _ in range(n)]</code> with the underscore <code>_</code> as a throw-away “loop variable” and the <code><a href="https://blog.finxter.com/python-dict/" data-type="post" data-id="19866">dict()</a></code> built-in dictionary creation function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [dict() for _ in range(10)]
print(my_list)
# [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
</pre>
<p>Note that if you update one of the dictionaries, all other dictionaries are unaffected by this because we really created n independent dictionary objects.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># update first dictionary:
my_list[0]['foo'] = 'bar' print(my_list)
# [{'foo': 'bar'}, {}, {}, {}, {}, {}, {}, {}, {}, {}]</pre>
<h2>Python Create Empty List of Class Objects</h2>
<p class="has-global-color-8-background-color has-background">To create an empty list of class objects, you can use list comprehension statement <code>my_list = [MyClass() for _ in range(n)]</code> that repeats <code>n</code> times the creation of an empty class object <code>MyClass</code> and adding it to the list. You can then later change the contents of the <code>n</code> different <code>MyClass</code> objects.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class MyClass(object): pass my_list = [MyClass() for _ in range(5)] print(my_list)
# [&lt;__main__.MyClass object at 0x000001EA45779F40>, &lt;__main__.MyClass object at 0x000001EA47533D00>, &lt;__main__.MyClass object at 0x000001EA475334C0>, &lt;__main__.MyClass object at 0x000001EA4758E070>, &lt;__main__.MyClass object at 0x000001EA4758E4F0>]</pre>
<h2>Python Create Empty List of Type</h2>
<p class="has-global-color-8-background-color has-background">Python is a dynamic language so there is no concept of a<em> “list of type X”</em>. Instead of creating a list of a fixed type, simply create an empty list using <code>[]</code> or <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list/" data-type="post" data-id="21502" target="_blank">list()</a></code> and assign it to a variable such as <code>my_list</code>. Using the variable, you can then fill into the existing list any data type you want!</p>
<p>Here we create an empty list and fill in an integer, a list, and a string—all into the same list!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = []
# Alternative: my_list = list() # Add integer to list:
my_list.append(42) # Add list to list:
my_list.append([1, 2, 3]) # Add string to list:
my_list.append('hello world') # Print all contents of list:
print(my_list)
# [42, [1, 2, 3], 'hello world']</pre>
<h2>Python Create Empty List of Integers</h2>
<p class="has-global-color-8-background-color has-background">To initialize a list with certain integers such as zeroes 0, you can either use the concise list multiplication operation <code>[0] * n</code> or you use list comprehension <code>[0 for _ in range(n)]</code>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> [0] * 5
[0, 0, 0, 0, 0]
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> [42] * 5
[42, 42, 42, 42, 42]
>>> [42 for _ in range(5)]
[42, 42, 42, 42, 42]</pre>
<h2>Python Create Empty List of Tuples</h2>
<p class="has-global-color-8-background-color has-background">To create an empty list and later add one <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuple</a> at-a-time to it, first initialize the empty list using the <code>[]</code> square bracket operator and then use the <code>list.append(t)</code> to append one tuple <code>t</code> at a time.</p>
<p>Here we add three tuples to the initially empty list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># create empty list:
my_list = [] # append tuples
my_list.append((1, 2))
my_list.append(('alice', 'bob', 'carl'))
my_list.append(tuple()) print(my_list)
# [(1, 2), ('alice', 'bob', 'carl'), ()]
</pre>
</div>


https://www.sickgaming.net/blog/2022/07/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016