Scripting

Python Arrays

Python Arrays

Introduction

An array is a collection of elements of the same data type stored in adjacent memory locations. Arrays make it easy to calculate the positions of elements.

They are useful when we only have to work with a specific data type value. The user can treat the list as an array and note the data type in the array must be the same. Now we’re gonna introduce you to using Array in Python. Hope you understand.

Example

animals = ["cat", "dog", "tiger"]

print(animals)

Output:

[‘cat’, ‘dog’, ‘tiger’]

Accessing array elements

Now, we will access the first item:

animals = ["cat", "dog", "tiger"]

x = animals[0]

print(x)

Output:

cat

For example, we will edit the value of the first item:

animals = ["cat", "dog", "tiger"]

animals[0] = "chicken"

print(animals)

Output:

[‘chicken’, ‘dog’, ‘tiger’]

The length of an array

Use len() function to print out the length of the array. For example:

animals = ["cat", "dog", "tiger"]

x = len(animals)

print(x)

Output:

3

Loop array elements

Using for in loop to iterate over each element of the array. For example, we will print out each item in the animals array:

animals = ["cat", "dog", "tiger"]

for x in animals:

print(x)

Output:

cat

dog

tiger

Conclusion

We just introduced you to how to use Array in Python.

Thank you for reading!

Similar Posts