current position:Home>Python Complete Guide -- tuple conversion array

Python Complete Guide -- tuple conversion array

2022-01-30 20:43:28 Stone sword

In this article , We will learn how to stay Python in hold Tuples transformation number Group .Python It's a great programming language . From the day it appeared , Its popularity is increasing day by day .Python How its unique advantages make it popular .

About Python

  1. An open source project
    1. Python Creator Guido Von Rossum Mr. made it an open source project when developing . He believes that keeping its free contribution will add more functions to it . More Than This , Different developers can also make it cross platform , And develop... For other fields . as time goes on , His idea finally succeeded .
    2. Developers are now contributing to it , Various modules are helping learners learn new concepts very easily .
  2. Huge library support
    1. Thanks to the contribution of open source , Various modules and libraries can be used . Each library is an independent task .
    2. These libraries are easy to add to python Environment .pip package (Package Installer for Python) Make it simple .
  3. Great developer support
    1. about Python, Developers are all over the world .
    2. They keep sending more and more advanced code , Make this project a better platform for coders .
  4. Optional fields
    1. There are various fields to choose from . machine learning , Data Science , Artificial intelligence , Network scraping , Network development , The Internet of things and cloud computing Some of these areas are .
    2. Core applications also include software development .
  5. Easy to learn and understand
    1. Python It's easy to learn and understand . It's very simple , One can complete basic arithmetic and input operations in one day .
    2. It is an object-oriented multi-purpose programming language , With the simplest class implementation .

Python Arrays and lists in

Considering that we need to create ten integer variables for some programming related work . We need to make some statements , obviously , This will include ten additional lines of code . Making such code is a tedious job . So we have arrays to solve this problem .

Python The array or list in is one of the most basic data structures to learn . They are a collection of elements belonging to one or more data types . The idea behind arrays is , We can access these elements multiple times . This also reduces many lines of code , And eliminates the creation of additional variables .

Python The difference between list and array in

list array
Elements with different data types . Elements that contain a single data type .
Iteratable through a loop Iteratable through a loop
It often operates in a one-dimensional model It often operates in one or more dimensions .

source -Python List vs Array

When everyone is confused between the two , The main problem arises . therefore , To make it clear , We will use code to apply

stay Python Declare a list in

Let us in Python Declare a list in


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

 Copy code 


List output

We can edit the list in various ways . These operations include

  1. Add new elements
  2. Remove elements
  3. Multiply element by external element .

1. Add a new element

**append()** Method to add a new element at the end of the list . This function takes the last element we need to add as a parameter .


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

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

 Copy code 

We can also use the concept of index to edit the list . An index is a positional number assigned to each element in a list and 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

 Copy code 

To access them , We need to call the list with this index number inside square brackets . In the following example , We will access the third element . remember , The index of positive numbers starts from 0 Start , Until n-1.


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

 Copy code 


  1. Index from 0 Start , from 0 To 2 The count is 3, Its output is 23. therefore , To access the third element , We need to invoke it in square brackets. 2.
  2. In the second line of code , We change the second by using the same properties 2 Elements of position .

2. Delete new elements

The main purpose of adding new elements is good , however , When we need to remove them from the list , There are also some operations . There are several functions that can help us delete objects .

  1. **clear()** Remove all elements from the list of functions , And return an empty list
  2. **pop()** The function takes an integer, index number, as an argument , Delete the element related to the index position .
  3. **remove()** Function removes the element we need to give it as an argument from the list .


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

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

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

 Copy code 


The list of operations

What is? Python In the array ?

Python There's a separate one ** Array operation library .** When we use Array When the module , We can feel something C Language programming experience .

We know that in this data structure , We can only store elements of the same data type . therefore , There are some special Unicode Character supply python The compiler recognizes the type of element or object in it .

To declare an array , There are a series of rules .array() The function requires some parameters . They are specific to specific data types .

The type of code C- type Python type
‘b’ Signed characters Integers
‘B’ An unsigned character Integers
‘u’ character An unsigned character
‘h’ Signed short code Integers
‘H’ Unsigned short code Integers
‘i’ Signed short code Integers
‘I’ Unsigned decimal Integers
‘l’ Signed long Integers
‘L’ Unsigned long Integers
‘q’ Signed long Integers
‘Q’ Unsigned long string Integers
‘f’ Floating point numbers float
‘d’ dual float

Appoint C Type special characters are used to make things clearer . These types represent the data types of the elements that exist in this particular array . The above code is some basic implementation methods .


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')

 Copy code 


Array operation

Array to list conversion

Other methods such as append(), pop() And so on are also applicable to this module . Through this link See more on the document page . Other special features include converting arrays to normal 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 code 

Array to list conversion

Be careful : In code type() Function returns the data type of the variable . through Over it , We check the data type of the array and convert the array to a list .

What is? Python Elements in ?

Python One of the most basic data structures in is ** Primitives **. Primitives are immutable data structures . We put the elements in parentheses , Separate them with commas . Once we create an element , There is no way to change or edit it directly .


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 code 

1. Retrieve elements in tuples

We can use Index method Access elements in tuples . Like a list , Elements in tuples are assigned index numbers .

tup = (2, 34, 1, -1, -4, 3)

 Copy code 

Tuple operation

Here we start with the fourth of the tuple 、 Extract the elements at the fifth and last positions .

Convert tuples into arrays and other data structures

Python Several functions and modules are provided to convert them into other data structures . Literally , They are simple lines of code .

Convert a tuple to an array

We will introduce two methods here . The first is to use Array module , The second is to use NumPy modular .

Use the array module to convert tuples into arrays

Before , The array module helps us declare pure arrays . however , We can also use it for conversion purposes . therefore , To make it clear , Let's use code to understand .

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 code 

Use array module for conversion


  1. Import array module .
  2. Declare a tuple . Print it on the screen .
  3. Then we use the array function . In this function The type of code by **'i' Of ** character . This will transform the tuple into an array of integers . In the next parameter , We separate our tuples with commas .
  4. Print the array on the screen .

Use Numpy The module converts tuples into arrays

Numpy- Numerical Python Is a very good library of array related operations . It is the developer's choice for complex mathematical calculation .

For this purpose , We use... In this library **array()** Method . This method converts tuples to NumPy Array , 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')

 Copy code 


Use Numpy Module conversion


  1. Import NumPy modular .
  2. Declare tuples and print them on the screen .
  3. Use type() Print data type .
  4. Declare a variable conv_tup And call **np.array()** Method , Where tuples are used as parameters .
  5. Print the converted tuple and its data type on the screen , To confirm the conversion result .

Convert tuples to a list


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

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

 Copy code 


  1. First , We declare a tuple as tup.
  2. then , Let's build a variable new_tup, Call again **list()** function , Give our tuple a parameter inside .
  3. It converts it into a normal list .
  4. Then we print it on the screen


therefore , Here we end python Topic of conversion from metagroup to array . These codes are very simple to implement , It's also easy to learn . therefore , Please trace each line of code and understand its function . This article also removes the concepts of lists and tuples .

copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.

Random recommended