Tuple To Array Conversion In Python – A Complete Guide

Convert Tuple To Array

In this article, we’ll learn how to convert a tuple to array in Python. Python is a great programming language. From its day of emergence till date the popularity is increasing day-by-day. There are some reasons why it is so popular among programming.

Quick Background About Python

  1. It is an opensource project
    1. The creator of Python Mr. Guido Von Rossum let it be an open-source project since its development. He believed that keeping it free for contribution will add more functionality to it. Not only this but different developers can also make it cross-platform and develop it for various other domains. His idea eventually got successful over time.
    2. Developers are now contributing to it and the various modules are helping the learners to learn various new concepts very easily.
  2. Huge library support
    1. Due to open source contributions, various modules and libraries are available. Each library is independent of independent tasks.
    2. The libraries are easy to add to the python environment. The pip package (Package Installer for Python) makes it easy.
  3. Great developer support
    1. The developers are all around the world for python.
    2. They keep sending more and more advanced codes to make this project a better platform for coders.
  4. Domains to choose from
    1. There are various domains for this. Machine Learning, Data Science, Artificial Intelligence, Web Scraping, Web Development, IoT and cloud computing etc. are some of these fields.
    2. The core application also includes Software Development.
  5. Easy to learn and understand
    1. Python is easy to learn and understand. It is as simple that one can clear the basic arithmetic and input operations within one day.
    2. It is an Object Oriented Multipurpose Programming Language that has the most easiest class implementation.

Array And Lists In Python

Consider that we need to create ten variables of integer type for some programming-related work. We need to make some declarations and obviously, that will cover ten extra lines of code. Making such codes is a tedious task. Thus we have arrays for this problem.

The arrays or lists in Python are one of the most fundamental data structures to learn. They are a collection of elements belonging to a single or multiple data types. The idea behind .an array is that we can access the elements multiple times. This also reduces the code with many lines and eliminates the creation of extra variables.

Difference between list and array in Python

ListArray
Contains elements of different data types.Contains elements of a single data type.
Iterable through a loopIterable through a loop
It is often operated in a one-dimensional modelIt is often operated in one dimension or multidimensions.
Source – Python List vs Array

The main problem occurs when everyone gets confused between these two. So, to make it clear we will apply with code

Declaring A List In Python

Let’s declare a list in Python

Code:

list1 = [23, 34, 12, 22] # declaring a list
print(list1) # printing the list on the screen

Output:

List Output
List Output

There are various ways through which we can edit the list. These operations involve:

  1. Adding new elements
  2. Deleting elements
  3. Multiplying the elements with external elements.

1. Adding new elements

The append() method adds new elements at the end of the list. This function takes the element that we need to add at the end as a parameter.

Code:

list1 = [11, 34, 23, 33, 4]
list1.append(2) # adds 2 at the end

# Output :-  [11, 34, 23, 33, 4, 2]

We can also edit the list using the indexing concept. An index is a position number that is assigned to each element in a list and also in the array. It starts from left to right and from right to left.

Code:

list1 = [23, 2, 4, 44]
#       0   1  2  3  positive indexing starts from left to right
#      -4 -3 -2 -1   negative indexing starts from right to left

To access them we need to call the list with that index number within square braces. In the below example we will access the third element. Remember that the positive index starts from 0 and goes on till n-1. 

Code:

list1 = [11, 34, 23, 33, 4]
print(list1[2])
# Output :- 23

Explanation:

  1. The indexing starts from 0 and from 0 to 2 the count is 3. It will give the output as 23. Thus, to access the third element we need to call 2 in the square brackets.
  2. In the second line of code, we change the element at the zeroth position by using the same property.

2. Deleting new elements

The main purpose of adding new elements is okay but, there are some operations when we need to remove them from the list. Several functions help to remove objects.

  1. clear() function removes all the elements from the list and returns it empty
  2. pop() function takes an integer which is the index number as a parameter and removes the element associated with that index position.
  3. remove() function removes the element from the list that we need to give inside it as a parameter.

Code:

list1 = [23, 89, 2, 3, -1, 12]
list1.clear() # deleting each element from the list
print(list1)

list1 = [23, 89, 2, 3, -1, 12]
list1.pop(4) # deleting the element from 4th index of the list
print(list1)

list1 = [23, 89, 2, 3, -1, 12]
list1.remove(-1) # search and remove the specified element from the list
print(list1)

Output:

List Operations 1
List Operations

What Is An Array In Python?

The Python has an independent library for the array operations. We can feel a somewhat C-programming experience when we work with the array module.

We know that we can only store elements of the same datatype in this data structure. So, there are special Unicode characters for the python compiler to identify what type of elements or objects are in it.

To declare an array there are a set of rules for this. The array() function takes some arguments. They are specific for specific data types.

Type Code C – typePython type
‘b’signed Characterinteger
‘B’unsigned Character integer
‘u’characterusigned character
‘h’signed short integer
‘H’unsigned short integer
‘i’signed int integer
‘I’unsigned int integer
‘l’signed long integer
‘L’unsigned long integer
‘q’signed long long integer
‘Q’unsigned long long integer
‘f’floatfloat
‘d’doublefloat

The C-type special characters are assigned to make things more clear. These types denote the data types of elements present inside that particular array. The above codes are some of the basic implementations. 

Code;

from array import *
int_array = array('i', [1, 4, 55, 51, -2])
print('\n Integer array: ',int_array)

char_array = array('u', ['a', 'b', 'c', 'd'])
print('\n Character array: ', char_array)

float_array = array('f', [2.2, 4.3, -1.2, 9.0])
print('\n Floating point array: ', float_array, '\n')

Output:

Array Operations
Array Operations

Conversion of array to list

Other methods like append(), pop(), etc. are also applicable for this module. View more at the documentation page through this link. Other special functions also include conversion of the array into a normal list – array.tolist().

Code:

from array import *

char_array = array('u', ['a', 'b', 'c', 'd'])
print('\n Character array: ', char_array)
print('Data type: ', type(char_array))

char_array = char_array.tolist()
print('\n','Converted array: ', char_array)
print('Data type: ', type(char_array))

Conversion Of Array To List
Conversion Of Array To List

Note: The type() function in the code returns the data type of the variable. Through this, we check the data type of array and convert the array to a list.

What Are Tuples in Python?

One of the most fundamental data structures in Python is the tuples. Tuples are immutable data structures. We enclose the elements inside the round brackets and separate them using commas. Once we create a tuple there is no direct way to change or edit that. 

Code:

tup = (3, 1, 2, 4, 5, 6) # declaration of a tuple
print(tup) # printing it on the screen

# output - (3, 1, 2, 4, 5, 6)

1. Retrieving the elements from tuple

We can access the elements from the tuple using the indexing methods. Just like lists, the elements in the tuple are assigned index numbers,

tup = (2, 34, 1, -1, -4, 3)
print(tup[3])
print(tup[4])
print(tup[-1])
Tuple
Tuple operations

Here we extract the elements from the fourth, fifth and last position from our tuple.

Convert Tuple to Array and other data structures

Python provides several functions and modules to convert them into other data structures. Literally, they are simple lines of code.

Converting a Tuple to Array

We will cover two methods here. The first is using the array module and the second uses NumPy module

Convert Tuple to Array using the Array module

Previously the array module helped us to declare pure arrays. But, we can also use it for conversion purposes. So, to make it clear let us understand with code.

from array import *

tup = (23, 98, 3, -2, -4, 11)
print('\n tuple: ', tup)
conv_tup = array('i', tup)
print('\n Converted tuple to an array: ',conv_tup, '\n')
Conversion Using Array Module
Conversion Using Array Module

Explanation:

  1. Import the array module.
  2. Declare a tuple. Print it on the screen.
  3. Then we use the array function. In that give the type code character as ‘i’. This will covert the tuple to an integer array. In the next argument, we give our tuple separating the commas.
  4. Print the array on the screen.

Convert Tuple to Array using the Numpy module

Numpy – numerical python is exceptionally a very good library for array-related operations. It is the developer’s choice for computations of complex mathematical calculations.

For this purpose, we use the array() method from this library. This method converts the tuple to a NumPy array which is ready for our use.

Code:

import numpy as np
tup = (23, 98, 3, -2, -4, 11)
print('\n tuple: ', tup)
print('Data type', type(tup))
conv_tup = np.array(tup)
print('\n Converted tuple to an array: ',conv_tup)
print('Data type', type(conv_tup),'\n')

Output:

Conversion Using Numpy Module
Conversion Using Numpy Module

Explanation:

  1. Importing the NumPy module.
  2. Declare the tuple and print it on the screen.
  3. Printing the data type using type().
  4. Declare a variable conv_tup and call the np.array() method inside which the tuple goes as a parameter.
  5. Print the converted tuple on the screen along with its data type to confirm the conversion.

Converting tuple into a list

Code:

tup = (2, 34, 2. -1, 9, 0) # declare a tuple
new_tup = list(tup) # converts tuple into list
print(new_tup)

# Output = [2, 34, 2. -1, 9, 0)]

Explanation:

  1. First, we declare a tuple as tup.
  2. Then we make a variable as new_tup and then we call the list() function inside that we give our tuple as a parameter.
  3. It converts it to an ordinary list.
  4. Then we print it on the screen

Conclusion

So, here we end the conversion topic of a tuple to array in python. These codes are very simple to implement and easy to learn. So, keep a track of each line of code and understand its functionality. This article also clears the concept regarding lists and tuples.