Set list size in python

Python: Initialize List of Size N

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we discuss how to initialize a list of size n in Python. We walk through an example of how to do this so you can initialize lists with custom sizes in your programs.

Python: Initialize List of Size N Using Multiplication

We’re going to build a leaderboard application that tracks the positions of the winners of a math tournament. This leaderboard will display the last eight students in the tournament.

Students are added in descending order. This is because the first student in the list is the winner and the eighth student is in the eighth place.

leaderboard = [None] * 8 print(leaderboard)

This code creates a list object with eight values. Each of the values in the list will be equal to None.

Читайте также:  Php curl add authorization header

Our code returns our list of None values:

[None, None, None, None, None, None, None, None]

The value None could be substituted with any default value that you want. For instance, you could make each default value an empty string (“”), the number zero (0), or something else.

The quarter-final has just completed and two contestants have been eliminated. The following contestants can now be added to our leaderboard:

To add these students to our list, we use the assignment notation:

leaderboard[7] = "Eileen" leaderboard[6] = "Chad"

We set the value of the item at position 7 to Eileen and the value at position 6 to Chad. This is because lists are indexed from zero. The first item in our list has the value 0 and the last item has the value 7. This means Eileen is last in our list and Chad is second from last.

Next, let’s write a “for” loop that displays all the positions in our leaderboard and the people who currently hold that position:

for l in range(0, len(leaderboard)): if leaderboard[l] != None: value = leaderboard[l] else: value = "TBD" print("<>: <>".format(l + 1, value))

We use a range() statement to create a list of values between 0 and the length of the “leaderboard” list. This lets us iterate over our list of students in the leaderboard while keeping track of each position.

In our loop, we check if the value at a particular position in the list is equal to None. If it is not, the value at that position is assigned to the variable “value”. Otherwise, the value “TBD” is assigned to the variable “value”.

Next, we print out the value of the “value” variable. We also print out the value of “l” plus one. This is because lists are indexed from zero and to show a rank we should add one to that value. Otherwise, our leaderboard would start from zero.

Let’s run our code and see what happens:

[None, None, None, None, None, None, None, None] 1: TBD 2: TBD 3: TBD 4: TBD 5: TBD 6: TBD 7: Chad 8: Eileen

Our code first prints out a list of None values. Next, our code assigns values to the last two items in our list. Finally, our code prints out the positions in our leaderboard.

Python: Initialize List of Size N Using range()

We can initialize a list of size n using a range() statement. The difference between using a range() statement and the None method is that a range() statement will create a list of values between two numbers. By default, range() creates a list from 0 to a particular value.

Let’s initialize our leaderboard list using a range() statement:

leaderboard = list(range(8)) print(leaderboard)

The range() statement creates a sequence of values between 0 and 7. We convert that sequence into a list so we can iterate over it. This is only necessary in Python 3.

Our code returns a new list with eight values:

Conclusion

You can initialize a list of a custom size using either multiplication or a range() statement.

The multiplication method is best if you want to initialize a list with the same values. A range() statement is a good choice if you want a list to contain values in a particular range.

Now you have the skills you need to initialize a Python list of size n like an expert!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

Set List Size in Python

Suppose you want to create a Python list of the predefined length? And suppose you want to create a list of lists with a certain size? Let’s find out what we can do in Python.

A quick answer

Creating a 1D list of elements

Method 1: Using the multiplication operator (*)

[None, None, None, None, None, None]

Method 2: Using a for-loop

Creating a list of lists (use for-loop)

[[None, None], [None, None], [None, None]]

Note: Be careful when creating these lists because things may not happen as you want them to. Please continue reading to find out what can go wrong and how to fix it.

Creating a list of predefined size

Often, programmers create an empty list and then append values to it. In some cases, however, we want a list of specific sizes, and then we can assign values. When creating the list, we will use some default values as placeholders, for example, the None value, an empty string (‘ ‘), etc.

The following are methods that can be used to create a Python list of a given size:

Method 1: Using multiplication operator (*)

a_list [None, None, None, None, None] b_list ['', '', '', '', ''] c_list [99, 99, 99, 99, 99] a_list modified [None, None, 27, None, None] IndexError: list assignment index out of range

In this snippet, we created lists of length 5 (you can use the len() function to check the length of a list) with different placeholders. We also show how to assign (using the ‘=’ operator) value to a list based on an index. Note that any attempt to assign value beyond the size of the list leads to IndexError.

Note: If you want to initialize a 2D list (lists within a list), don’t use the multiplication operator, it will give you results you might not expect (we will discuss this in the next section).

Method 2: Using for-loop

We can also use a for loop to create lists of a pre-decided size. For example,

And we can convert this into a list expression as follows:

['None', 'None', 'None', 'None', 'None', 'None', 'None']

Creating Python list of lists (2D) of predefined sizes

The use of the multiplication operator only works for non-referenced data types like numbers, None, and strings but may not work as you expect for types like lists and sets. For this reason, the use of the multiplication operator is avoided.

What goes wrong?

Let’s see what happens when we use the multiplication operator for initializing a list with referenced elements like lists.

[[None, None], [None, None], [None, None]] [[23, None], [23, None], [23, None]] [[23, None, 'foo'], [23, None, 'foo'], [23, None, 'foo']]

On inspection of the printout, the created list in line 2 seems OK, but it is not. To show that, we attempted to assign the value 23 to the first element in the first list. We expected to get [[23, None], [None, None], [None, None]] but we got unusual results. Attempting to append also did not yield the results we wanted. Just like me, you might have expected [“foo”, [None, None], [None, None]]. So what exactly went wrong?

The problem is with references. The object we created creates a list of pointers. Using a multiplication operator with any non-primitive (referenced) object will create a list of pointers to the same object. We can confirm that by using the id() function in Python, which tells us the identity of .

[139675625121024, 139675625121024, 139675625121024]

As you can see, the IDs are the same, meaning each element is pointing to the same list object.

The correct way to do it (use for loop)

The best way to create an initialized list within a list is to use for-loop unless you fully understand the above potential issue and fits what you want to do.

Источник

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.

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 .

  • zip() in Python: Get elements from multiple lists
  • Pretty-print with pprint in Python
  • List comprehensions in Python
  • Random sampling from a list in Python (random.choice, sample, choices)
  • Check if a list has duplicates in Python
  • Extract, replace, convert elements of a list in Python
  • Unpack a tuple and list in Python
  • Convert numpy.ndarray and list to each other
  • Reverse a list, string, tuple in Python (reverse, reversed)
  • Remove/extract duplicate elements from list in Python
  • Count elements in a list with collections.Counter in Python
  • Apply a function to items of a list with map() in Python
  • Sort a list, string, tuple in Python (sort, sorted)
  • Add an item to a list in Python (append, extend, insert)
  • Unpack and pass list, tuple, dict to function arguments in Python

Источник

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