Signed and Unsigned Integer Arrays in Python

Python | Signed and Unsigned Integer Array: Here, we are going to learn how to declare, use unsigned and signed integer array in Python?
By IncludeHelp Last updated : September 15, 2023

An array can be declared by using "array" module in Python.

Syntax to import "array" module:

import array as array_alias_name

Here, import is the command to import Module, "array" is the name of the module and "array_alias_name" is an alias to "array" that can be used in the program instead of module name "array".

Array declaration

To declare an "array" in Python, we can follow following syntax:

array_name = array_alias_name.array(type_code, elements)

Here,

  • array_name is the name of the array.
  • array_alias_name is the name of an alias - which we define importing the "array module".
  • type_code is the single character value – which defines the type of the array elements is the list of the elements of given type_code.

Declaring Signed and Unsigned Integer Array

Signed Integer is defined by using type_code "i" (small alphabet "i") and it contains negative and posited integers.

Unsigned Integer is defined by using type_code "I" (Capital alphabet "I") and it contains only positive integers.

Examples to declare and initialize "unsigned" and "signed" integer array in Python

# unsigned integer array 
a = arr.array ("I", [10, 20, 30, 40, 50])
# signed integer array 
b= arr.array ("i", [10, -20, 30, -40, 50])

Program

# importing array class to use array 
import array as arr

# an unsigned int type of array 
# declare and assign elements 
a = arr.array ("I", [10, 20, 30, 40, 50] )
# print type of a 
print ("Type of a: ", type (a))
# print array 
print ("Array a is: ")
print (a)

# a signed int type of array 
# declare and assign elements 
b = arr.array ("i", [10, -20, 30, -40, 50] )
# print type of a 
print ("Type of b: ", type (a))
# print array 
print ("Array b is: ")
print (b)

Output

Type of a:  <class 'array.array'>
Array a is:
array('I', [10, 20, 30, 40, 50])
Type of b:  <class 'array.array'>
Array b is:
array('i', [10, -20, 30, -40, 50])

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.