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
- It is an opensource project
- 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.
- Developers are now contributing to it and the various modules are helping the learners to learn various new concepts very easily.
- Huge library support
- Due to open source contributions, various modules and libraries are available. Each library is independent of independent tasks.
- The libraries are easy to add to the python environment. The pip package (Package Installer for Python) makes it easy.
- Great developer support
- The developers are all around the world for python.
- They keep sending more and more advanced codes to make this project a better platform for coders.
- Domains to choose from
- 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.
- The core application also includes Software Development.
- Easy to learn and understand
- Python is easy to learn and understand. It is as simple that one can clear the basic arithmetic and input operations within one day.
- 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
|Contains elements of different data types.||Contains elements of a single data type.|
|Iterable through a loop||Iterable through a loop|
|It is often operated in a one-dimensional model||It is often operated in one dimension or multidimensions.|
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
list1 = [23, 34, 12, 22] # declaring a list print(list1) # printing the list on the screen
There are various ways through which we can edit the list. These operations involve:
- Adding new elements
- Deleting elements
- 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.
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.
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.
list1 = [11, 34, 23, 33, 4] print(list1) # Output :- 23
- 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.
- 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.
- clear() function removes all the elements from the list and returns it empty
- pop() function takes an integer which is the index number as a parameter and removes the element associated with that index position.
- remove() function removes the element from the list that we need to give inside it as a parameter.
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)
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 – type||Python type|
|‘q’||signed long long||integer|
|‘Q’||unsigned long long||integer|
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.
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')
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().
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))
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.
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) print(tup) print(tup[-1])
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')
- Import the array module.
- Declare a tuple. Print it on the screen.
- 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.
- 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.
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')
- Importing the NumPy module.
- Declare the tuple and print it on the screen.
- Printing the data type using type().
- Declare a variable conv_tup and call the np.array() method inside which the tuple goes as a parameter.
- Print the converted tuple on the screen along with its data type to confirm the conversion.
Converting tuple into a list
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)]
- First, we declare a tuple as tup.
- Then we make a variable as new_tup and then we call the list() function inside that we give our tuple as a parameter.
- It converts it to an ordinary list.
- Then we print it on the screen
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.