- Python return array
- Answer by Juliette McKee
- Answer by Briar Santiago
- Answer by Isabella Romero
- The Length of an Array
- Answer by Yahir Tang
- Answer by Avi Haynes
- Answer by Charli Olsen
- Answer by Araceli Harrington
- Answer by Hattie Peck
- Example: python return array
- Using Arrays with Python Ctypes
- Creating Arrays with Ctypes
- Converting an existing list to Array
- Returning Arrays from C into Python
Python return array
In Python, we can return multiple values from a function. Following are different ways,Returning Multiple Values in Python,3) Using a list: A list is like an array of items created using square brackets. They are different from arrays as they can contain items of different types. Lists are different from tuples as they are mutable.,Python map() function
Answer by Juliette McKee
def my_function(): result = [] #body of the function return result
Answer by Briar Santiago
Your function is correct. When you write return my_array,my_variable, your function is actually returning a tuple (my_array, my_variable).,I tried returning a tuple but got the unhashable type message for np.array, If you want to return a tuple, it should be (my_array, my_variable). Using curly brackets is returning dict, which requires the element to be hashable, in this case, list is not. – justhalf Oct 22 ’13 at 1:25 ,Is there a simple way to get a function to return a np.array and a variable?
You can first assign the return value of my_function() to a variable, which would be this tuple I describe:
Next, since you know how many items are in the tuple ahead of time, you can unpack the tuple into two distinct values:
result_array, result_variable = result
Or you can do it in one line:
result_array, result_variable = my_function()
I sometimes keep the two steps separate, if my function can return None in a non-exceptional failure or empty case:
result = my_function() if result == None: print 'No results' return a,b = result # .
Instead of unpacking, alternatively you can access specified items from the tuple, using their index:
result = my_function() result_array = result[0] result_variable = result[1]
If for whatever reason you have a 1-item tuple:
You can unpack it with the same (slightly awkward) one-comma syntax:
Answer by Isabella Romero
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.,Use the len() method to return the length of an array (the number of elements in an array).,Return the number of elements in the cars array:,You can use the pop() method to remove an element from the array.
The Length of an Array
Use the len() method to return the length of an array (the number of elements in an array).
Answer by Yahir Tang
Length of an array is the number of elements that are actually present in an array. You can make use of len() function to achieve this. The len() function returns an integer value that is equal to the number of elements present in that array.,This returns a value of 3 which is equal to the number of array elements.,Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.,The result will be elements present at 1st, 2nd and 3rd position in the array.
a=arr.array(data type,value list) #when you import using arr alias
a=array(data type,value list) #when you import using *
a=arr.array( 'd', [1.1 , 2.1 ,3.1] ) a[1]
a=arr.array('d', [1.1 , 2.1 ,3.1] ) len(a)
a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.append(3.4) print(a)
a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.extend([4.5,6.3,6.8]) print(a)
a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.insert(2,3.8) print(a)
Any two arrays can be concatenated using the + symbol.
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8]) b=arr.array('d',[3.7,8.6]) c=arr.array('d') c=a+b print("Array c = ",c)
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6]) print(a.pop()) print(a.pop(3))
a=arr.array('d',[1.1 , 2.1 ,3.1]) a.remove(1.1) print(a)
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8]) print(a[0:3])
Using the for loop, we can loop through an array.
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6]) print("All values") for x in a: print(x) print("specific values") for x in a[1:3]: print(x)
Answer by Avi Haynes
Return the number of occurrences of x in the array.,Insert a new item with value x in the array before position i. Negative values are treated as being relative to the end of the array.,Return the smallest i such that i is the index of the first occurrence of x in the array.,Convert the array to an ordinary list with the same items.
array('l') array('u', 'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.14])
Answer by Charli Olsen
Compute for each element of the array, it’s final position in the rotated array and simply move it there.,Connect and share knowledge within a single location that is structured and easy to search.,Please be sure to answer the question. Provide details and share your research!, With a separation of 1000 feet, in flight is there any danger of severe wake turbulence?
Not sure if you know the obvious solution and just want to re-invent the wheel or if you are just not aware of this but you could just do :
>>> l = [1, 2, 3, 4, 5, 6] >>> n = 2 >>> l[-n:] + l[:-n] [5, 6, 1, 2, 3, 4]
After fixing all this, you get something like :
def copy_digit(lst, index, item): """ Copy the item to the indexed location in the given list """ lst[index] = item return lst def rotate_list(lst, nb_rotate): """ Rotate List to right """ print("Function received ,".format(lst, nb_rotate)) for rotate in range(N): last_item = lst[-1] for i in range(len(lst) - 2, -1, -1): item_to_shift = lst[i] lst = copy_digit(lst, i + 1, item_to_shift) lst[0] = last_item print("Rotate once: ".format(lst)) return lst if __name__ == '__main__': """ This program will rotate right the given list N no of times """ array = [1, 2, 3, 4, 5, 6] N = 2 print("Rotate an array: ", array, "No of times: ", N) final_list = rotate_list(array, N) print("Rotated List: ", final_list)
final_list = rotate_list(array, 2)
Your function copy_digit updates the list and returns it. There is no real need for this as the caller would already have the initial list. Then you can just have :
def copy_digit(lst, index, item): """ Copy the item to the indexed location in the given list """ lst[index] = item
. copy_digit(lst, i + 1, item_to_shift) .
Of course, the need for a function seems a bit doubtful here. Let’s inline this :
Then, it seems like the item_to_shift variable is not really required anymore :
for i in range(len(lst) - 2, -1, -1): lst[i + 1] = lst[i]
Answer by Araceli Harrington
In Python, you can return multiple values by simply return them separated by commas.,As an example, define a function that returns a string and a number as follows: Just write each value after the return, separated by commas.,Define and call functions in Python (def, return),Each element has a type defined in the function.
Answer by Hattie Peck
Example: python return array
def my_function(): result = [] #body of the function return result
Using Arrays with Python Ctypes
In this Python tutorial we will discuss how to pass Arrays back and forth between our C and Python programs using the ctypes library.
Arrays in Python, and Arrays in C/C++ are created and handled in very different ways. Luckily, Ctypes exists as a medium between C and Python, thanks to which creating C-compatible arrays is possible in Python. Lets explore how we can do this.
Creating Arrays with Ctypes
Lets start off by trying to do something rather simple. Unfortunately when dealing when ctypes, even the simplest thing can become rather complex. (It’s worth it for the performance though).
We will be creating an array of integers in our Python file, and a function which sums the elements of an array and returns the result in our C program. We will pass this array to our C file, get the result and print it out in our Python file.
First we need to create our C function.
int sum(int *arr, int n) < int sum = 0; for (int i = 0; i < n; i++) < sum += arr[i]; >return sum; >
This is a basic function that takes two parameters. A pointer to an array, and the size of the array. We then iterate through the array, calculate the sum and then return it.
Lets give our C program a quick compile now by running the following command in our command prompt:
gcc -fPIC -shared -o clibrary.so cpplibrary.c
Likewise, if we had a .cpp file we would instead do the following:
g++ -fPIC -shared -o cpplibrary.so cpplibrary.cpp
Note: These names are completely arbitrary. Only the extensions matter here.
Now that our shared library (the .so file) is generated, we can move back to our Python file. We used some fancy code using the os module to automatically generate the full file path for our shared file (under the assumption that both the python file and shared library are in the same directory). You can change this behavior if you run into any issues (just write the raw file path).
import ctypes import os import time path = os.getcwd() clibrary = ctypes.CDLL(os.path.join(path, 'clibrary.so'))
Now we need to create our Python array.
In ctypes, the way to do this is to multiply a normal datatype (like c_int ) by the number of elements you want in the array. The empty () brackets count as a constructor of sorts. Don’t forget to include it.
Next we will fill in some values into our array (from 1 to 10). This way we have basically converted our C-array pointer to a Python-list.
for i in range(10): array[i] = i
Finally, we will pass this array and its size into our sum() function from our clibrary.
x = clibrary.sum(array, len(array)) print(clibrary.sum(array, 10))
As you can see, we have the correct output here! 45 is the sum of numbers from 1 to 10.
Converting an existing list to Array
Here is a slight bonus trick that you can use to quickly convert an existing Python list into a Ctypes Array.
values = [5, 7, 8, 3, 6, 8, 9, 6, 3, 2] array = (ctypes.c_int * 10)(*values) x = clibrary.sum(array, len(array)) print(clibrary.sum(array, 10))
Note: The * asterisk next to values is being used to “unpack” the list into individual values.
Returning Arrays from C into Python
First we will create a function in our C program which returns an array of numbers.
#include #include int* getArray() < int *array = (int*) malloc(10 * sizeof(int)); for (int i = 0; i return array; >
(Remember to recompile your library before proceeding)
Back to our Python file now. We will need to first explicitly define the return type of the getArray() function as a “integer pointer” using the restype attribute (part of the function signature in ctypes). (We usually need to do this with functions that return pointers in C)
import ctypes import os path = os.getcwd() clibrary = ctypes.CDLL(os.path.join(path, 'lib.so')) clibrary.getArray.restype = ctypes.POINTER(ctypes.c_int) x = ctypes.POINTER(ctypes.c_int) x = clibrary.getArray()
Next we will create a ctypes pointer which points to an integer, called “x”. We will store the return value from our getArray() function in here.
After we call getArray() and store the result in x, we now have a pointer to an array of numbers. But what now?
Well we can access it using regular Python list indexing. The below code shows us how we can iterate over it and print out its values.
The only slight problem here, is that we cannot determine from the pointer what the size of the array is. One way of overcoming this would be to wrap the array in a struct with an attribute for size, and then return the struct instead.
A similar concept that you might be interested in, is the handling of structs in Ctypes. You can create custom Classes in Python, which you can then pass into your C program with the help of Ctypes. Interested in learning how? Follow the link for more!
This marks the end of the Arrays with Python Ctypes Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.