In this article, we’ll learn how to convert tuples to arrays in Python. Python is a great programming language. Since the day it appeared, its popularity has grown. Python’s unique advantages have made it popular.
About the Python
- An open source project
- Guido Von Rossum, Python’s creator, made it an open source project when it was developed. He thinks keeping it free will add more features to it. Not only that, different developers can make it cross-platform and develop it for a variety of other domains. As time went on, his idea eventually took off.
- Developers are now contributing to it, and modules are helping learners learn new concepts very easily.
- Great library support
- Thanks to open source contributions, various modules and libraries are available. Each library is an independent task.
- These libraries are easy to add to the Python environment. The PIP Package Installer for Python makes this easy.
- Great developer support
- With Python, developers are all over the world.
- They keep sending out more and more advanced code, making the project a better platform for coders.
- Optional fields
- There are various fields to choose from. Machine learning, data science, artificial intelligence, web scraping, web development, the Internet of Things, and cloud computing are just some of these areas.
- Core applications also include software development.
- Easy to learn and understand
- Python is easy to learn and understand. It is so simple that a person can complete basic arithmetic and input operations in a day.
- It is an object-oriented multipurpose programming language with the simplest class implementation.
Arrays and lists in Python
Consider that we need to create variables of type ten integer for some programming-related work. We need to make some declarations, which will obviously include ten extra lines of code. Making such code is a tedious task. So we have arrays to solve this problem.
Arrays or lists in Python are one of the most basic data structures to learn. They are collections of elements belonging to one or more data types. The idea behind arrays is that we can access these elements multiple times. This also reduces many lines of code and eliminates the creation of extra variables.
The difference between lists and arrays in Python
The list of | array |
Contains elements of different data types. | An element that contains a single data type. |
Iterability through loops | Iterability through loops |
It often operates in one-dimensional models | It often operates in one or more dimensions. |
Source -Python List vs Array
The main problem comes when everyone is confused between the two. So, to make it clear, we’re going to apply it in code
Declare 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
Copy the code
The output
The list of output
We can edit lists in various ways. These operations include
- Add new elements
- Remove elements
- Multiply an element by an external element.
1. Add new elements
The **append()** method adds a new element at the end of the list. This function takes as an argument the element we need to add to the end.
code
list1 = [11, 34, 23, 33, 4]
list1.append(2) # adds 2 at the end
# Output :- [11, 34, 23, 33, 4, 2]
Copy the code
We can also use the concept of indexes to edit lists. An index is a positional number assigned to each element in a list and array. It starts from left to right and 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
Copy the code
To access them, we need to call the list with the index number inside square brackets. In the following example, we will access the third element. Remember, the index of positive numbers starts at 0 and goes up to n minus 1.
code
list1 = [11, 34, 23, 33, 4]
print(list1[2])
# Output :- 23
Copy the code
explain
- The index starts at 0, the count from 0 to 2 is 3, and its output is 23. Therefore, in order to access the third element, we need to call 2 in square brackets.
- In the second line of code, we change the element in position 2 by using the same attribute.
2. Delete the new element
The main purpose of adding new elements is good, but there is also something to do when we need to remove them from the list. There are several functions that can help us delete objects.
- The **clear()** function removes all elements from the list and returns an empty list
- The **pop()** function takes an integer, the index number, and deletes the element associated with the index position.
- The **remove()** function removes the element we need to give it as an argument from the list.
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)
Copy the code
The output
The list of operations
What is an array in Python?
Python has a separate library of ** array operations. ** We can feel some degree of C programming experience when we use the array module.
We know that in this data structure, we can only store elements of the same data type. So, there are special Unicode characters for the Python compiler to recognize the type of element or object in.
To declare an array, there are a number of rules. The array() function takes some arguments. They are specific to a specific data type.
The type of code | C – type | Python types |
“B” | Signed characters | The integer |
“B” | Unsigned character | The integer |
‘u’ | character | Unsigned character |
‘h’ | Signed short code | The integer |
‘H’ | Unsigned short code | The integer |
‘I’ | Signed short code | The integer |
‘I’ | Unsigned decimal | The integer |
‘l’ | A signed long | The integer |
‘L’ | Unsigned long | The integer |
“Q” | There’s a sign length | The integer |
“Q” | A long unsigned string | The integer |
‘f’ | Floating point Numbers | float |
‘d’ | dual | floating |
The C special character is specified to make things clearer. These types represent the data types of the elements that exist in that particular array. The code above is some 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: ', \n')Copy the code
The output
An array of operating
Array to list conversion
Other methods such as append(), pop() and so on are also available in this module. Follow this link to see more on the documentation page. Other special features include converting arrays to plain lists –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))
Copy the code
Array to list conversion
Note: The type() function in this code returns the data type of the variable. With this, we check the data type of the array and convert the array to a list.
What are primitives in Python?
One of the most basic data structures in Python is primitives. Primions are immutable data structures. We put the elements in parentheses, separating them with commas. Once we have created a primitive, there is no way to change or edit it directly.
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)
Copy the code
1. Retrieve elements in a tuple
We can use index methods to access elements in tuples. Just like a list, elements in a tuple are assigned index numbers.
tup = (2, 34, 1, -1, -4, 3)
print(tup[3])
print(tup[4])
print(tup[-1])
Copy the code
Yuan set of operations
Here we extract elements from the fourth, fifth, and last position of the tuple.
Convert tuples to arrays and other data structures
Python provides several functions and modules to convert them into other data structures. They are literally simple lines of code.
Converts a tuple to an array
We will introduce two approaches here. The first is to use the array module, and the second is to use the NumPy module.
Use the array module to convert tuples to arrays
Previously, the array module helped us declare pure arrays. However, we can also use it for transformation purposes. So, for clarity, let’s understand it in 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')
Copy the code
Use the array module for conversion
instructions
- Import the array module.
- Declare a tuple. Print it on the screen.
- Then we use the array function. Give the ** character with type code **’ I ‘in this function. This will turn the tuple into an array of integers. In the next argument, we separate our tuples with commas.
- Print the array on the screen.
Use the Numpy module to convert tuples to arrays
Numpy- Numeric Python is a great library for array-related operations. It is the developer’s choice for complex mathematical calculations.
For this purpose, we use the **array()** method in this library. This method converts tuples into NumPy arrays 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')
Copy the code
The output
Use Numpy module for conversion
explain
- Import the NumPy module.
- Declare a tuple and print it on the screen.
- Print the data type using type().
- Declare a variable conv_tup and call the **np.array()** method with tuples as arguments.
- Print the converted tuple and its data type on the screen to confirm the result of the conversion.
Converts a tuple to 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)]
Copy the code
explain
- First, we declare a tuple as tUP.
- We then create a variable new_tup and call the **list()** function to give our tuple an argument.
- It turns it into a normal list.
- And then we print it on the screen
conclusion
So, here we finish the topic of tuple to array conversions in Python. The code is simple to implement and easy to learn. So follow each line of code and understand its function. This article also clears up the concept of lists and tuples.