• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] How to Convert List of Lists to NumPy Array?

How to Convert List of Lists to NumPy Array?

Short answer: Convert a list of lists—let’s call it `l`—to a NumPy array by using the standard `np.array(l)` function. This works even if the inner lists have a different number of elements.

Convert List of Lists to 2D Array

Problem: Given a list of lists in Python. How to convert it to a 2D NumPy array?

Example: Convert the following list of lists

`[[1, 2, 3], [4, 5, 6]]`

into a NumPy array

`[[1 2 3] [4 5 6]]`

Solution: Use the `np.array(list)` function to convert a list of lists into a two-dimensional NumPy array. Here’s the code:

```# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array
a = np.array(lst) # Print the resulting array
print(a) '''
[[1 2 3] [4 5 6]] '''```

Try It Yourself: Here’s the same code in our interactive code interpreter:

`<iframe height="700px" width="100%" src="https://repl.it/@finxter/numpylistoflists?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>`

Hint: The NumPy method `np.array()` takes an iterable as input and converts it into a NumPy array.

Convert a List of Lists With Different Number of Elements

Problem: Given a list of lists. The inner lists have a varying number of elements. How to convert them to a NumPy array?

Example: Say, you’ve got the following list of lists:

`[[1, 2, 3], [4, 5], [6, 7, 8]]`

What are the different approaches to convert this list of lists into a NumPy array?

Solution: There are three different strategies you can use. (source)

(1) Use the standard `np.array()` function.

```# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array
a = np.array(lst) # Print the resulting array
print(a) '''
[list([1, 2, 3]) list([4, 5]) list([6, 7, 8])] '''```

This creates a NumPy array with three elements—each element is a list type. You can check the type of the output by using the built-in `type()` function:

```>>> type(a)
<class 'numpy.ndarray'>```

(2) Make an array of arrays.

```# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array
a = np.array([np.array(x) for x in lst]) # Print the resulting array
print(a) '''
[array([1, 2, 3]) array([4, 5]) array([6, 7, 8])] '''```

This is more logical than the previous version because it creates a NumPy array of 1D NumPy arrays (rather than 1D Python lists).

(3) Make the lists equal in length.

```# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list
n = len(max(lst, key=len)) # Make the lists equal in length
lst_2 = [x + [None]*(n-len(x)) for x in lst]
print(lst_2)
# [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array
a = np.array(lst_2) # Print the resulting array
print(a) '''
[[1 2 3 None] [4 5 None None] [6 7 8 9]] '''
```

You use list comprehension to “pad” `None` values to each inner list with smaller than maximal length.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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!

https://www.sickgaming.net/blog/2020/04/...mpy-array/

Forum Jump:

 Users browsing this thread: 1 Guest(s)

 Active Threads Are you still excited about the resurrec... Last Post: Ulrica Today 03:24 AM » Replies: 0 » Views: 6 Can the player have two animal crossings... Last Post: Sellen Today 02:58 AM » Replies: 0 » Views: 9 (Indie Deal) Cozy Grove, Iceberg, The Cr... Last Post: xSicKxBot Today 02:47 AM » Replies: 0 » Views: 3 Microsoft - Aliens: Fireteam Elite avail... Last Post: xSicKxBot Today 02:47 AM » Replies: 0 » Views: 2 News - GamesMaster: Episode 2 Heaps Prai... Last Post: xSicKxBot Today 02:47 AM » Replies: 0 » Views: 2 News - Stardew Valley Patch 1.5.5 Adds E... Last Post: xSicKxBot Today 02:47 AM » Replies: 0 » Views: 2 (Indie Deal) Tales of Arise, Paradox, Ko... Last Post: xSicKxBot Yesterday 11:09 PM » Replies: 0 » Views: 14 News - Looks Like Pokémon GO’s Next Seas... Last Post: xSicKxBot Yesterday 11:09 PM » Replies: 0 » Views: 3 [Tut] How to Deploy a Smart Contract on ... Last Post: xSicKxBot Yesterday 03:57 PM » Replies: 0 » Views: 18 (Indie Deal) Anime Giveaways, Nerf Legen... Last Post: xSicKxBot Yesterday 03:57 PM » Replies: 0 » Views: 4