How to create a Array (not using list) in Python


If you come from C++, C#, or Java background, we all know arrays are a separate data type, but in Python most we hear is we can make use of a list for arrays. But do you know there is an array module that you can make use of specifically to create array types.

Using the array's module we can create a more memory-efficient array type that allows us to store elements of the same data type.


Example 1: Array of Integers

import array

int_array = array.array('i', [1, 2, 3, 4, 5])

print(int_array)

Example 2: Array of floats

import array

int_array = array.array('f', [1.5, 2.5, 3.9, 4, 50.1])
print(int_array)

List of types in Python Arrays

    Type code C Type Python Type Minimum size in bytes
    'b' signed char int 1
    'B' unsigned char int 1
    'u' wchar_t str 2
    'h' signed short int 2
    'H' unsigned short int 2
    'i' signed int int 2
    'I' unsigned int int 2
    'l' signed long int 4
    'L' unsigned long int 4
    'q' signed long long int 8
    'Q' unsigned long long int 8
    'f' float float 4
    'd' double float 8

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap