python basic concept – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Fri, 20 Nov 2020 18:21:26 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 python basic concept – Java2Blog https://java2blog.com 32 32 How to initialize array in Python https://java2blog.com/initialize-array-python/?utm_source=rss&utm_medium=rss&utm_campaign=initialize-array-python https://java2blog.com/initialize-array-python/#respond Fri, 20 Nov 2020 18:21:26 +0000 https://java2blog.com/?p=10987 In this article, we will see a different ways to initialize an array in Python.

Array is collection of elements of same type. In Python, we can use Python list to represent an array.

Using for loop, range() function and append() method of list

Let’s see different ways to initiaze arrays

Intialize empty array

You can use square brackets [] to create empty array.

# empty array
arr = []

print('Empty array: ', arr)
Empty array: []

Intialize array with default values

Here, we are adding 0 as a default value into the list for n number of times using append() method of list. for looping each time we are using for loop with range() function.

Below is the Python code given:

# number of elements
n = 10

# empty array
arr = []

defaultValue = 0

# loop 
for i in range(n) :

    # add element
    arr.append(defaultValue)

print(arr)

Here range() function is used to generate sequence of numbers. We are using range(stop) to generate list of numbers from 0 to stop.
Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Intialize array with values

You can include elements separated by comma in square brackets [] to initialize array with values.

arr = [10, 20, 30, 40]
print(arr)
[10, 20, 30, 40]

Using list-comprehension

Here, list-comprehension is used to create a new list of n size with 0 as a default value.

Below is the Python code given:

# number of elements
n = 10

defaultValue = 0

# make a array of n elements
arr = [ defaultValue for i in range(n)]

print(arr)

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Using product (*) operator

Here, product operator (*) is used to create a list of n size with 0 as a default value.

Below is the Python code given:

# number of elements
n = 10

defaultValue = 0

# array of n elements
arr = [defaultValue] * n

print(arr)

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Using empty() method of numpy module

here, empty() method of numpy is used to create a numpy array of given size with default value None.

Below is the Python code given:

# import numpy module
import numpy

# number of elements
n = 10

# array of n elements
arr = numpy.empty(n, dtype = object)

print(arr)

Output:

[None None None None None None None None None None]

That’s all about how to initialize array in Python.

]]>
https://java2blog.com/initialize-array-python/feed/ 0