- HTML Comments Tutorial | Convert Comments into HTML Codes
- Data Structure and Algorithms Tutorial | Ultimate Guide to Learn
- Gradle Tutorial | For Beginners [ STEP-IN ]
- Encapsulation In Java | Complete Tutorial With Examples
- What is Release Management? | A Comprehensive Tutorial for Beginners
- OOPs Concepts in Java | Learn from Basics with Examples
- The Top Basic Tools of Quality Tutorial | The Ultimate Guide
- Set Environment for C# – Learn How to Setup through this Tutorial
- C# Vs Java Tutorial | Overview and Key Difference
- List of IDEs to run C# Programs | Tutorial for Learning Path
- C Sharp Variables and Constants | The Ultimate Guide
- Unsafe Code in C-Sharp Tutorial | Everything You Need to Know
- Type Conversion Method in C# | A Complete Tutorial
- What Is Synchronization in c# Tutorial | The BEST Step-By-Step Guide
- Understanding Structures in C# | Learn in 1 Day FREE Tutorial
- Strings – C# Tutorial | A Definitive Programming Guide
- Static Keyword in C# Tutorial | Learn with Examples
- Stack Collection in C# Tutorial | A Definitive Guide for Beginners
- C# Sorted List Tutorial with Examples | Learn in 1 Day FREE
- C# Serialization Tutorial | Ultimate Guide to Learn [BEST & NEW]
- Regular Expression in C# Tutorial | Everything You Need to Know
- What is Reflection in C#? | Learn Now Tutorial
- Queue Collection in C# Tutorial | A Definitive Guide
- Properties in C# | The complete Tutorial
- C# Preprocessor Directives Tutorial | Learn in 1 Day FREE
- Polymorphism C# Tutorial | The Ultimate Guide
- C# Operators Tutorial | Learn Arithmetic, Comparison, Logical Concepts
- Namespaces – The complete C# Tutorial
- Multithreading in C# Tutorial | Learn With Examples and Advantages
- Methods – C# Tutorial | A Complete Programming Guide
- Linked List Implementation in C# Tutorial | Ultimate Guide to Learn [UPDATED]
- Introduction to C# Tutorial | Guide for Beginners
- What is Interface in C# | A Defined Free Tutorial
- C# Inheritance Tutorial | A Complete Free Tutorial
- Indexers in C# Tutorial | A Complete Programming Guide
- HashSet Collection in C# Tutorial | Complete Guide Tutorial For Free
- Generics in C# Tutorial | Learn Generic Classes and Methods
- Creating Your First C# Program Tutorial | Learn in 1 Day
- Basics of File Handling in C# Tutorial | The Ultimate Guide
- C# Exception Handling Tutorial | Learn with Best Practices
- Events – C# Tutorial | A Complete Programming Guide
- C# Enumerations Type Tutorial | Learn Everything about Enum
- Dictionary Collection in C# | Ultimate Guide to Learn [NEW & UPDATED]
- Delegates – C# Programming Guide | The Ultimate Guide for Beginners
- Understanding Decision Making Statements in C# | Learn Now Tutorial
- Classes and Objects – C# Fundamentals Tutorial
- C# BitArray Collection Tutorial | Learn in 1 Day FREE
- Attributes in C# Tutorial | Learn to work with attributes in C#
- C# Array Tutorial | Create, Declare, Initialize
- ArrayList Collection on in C# | A Complete tutorial For Beginners
- Anonymous Methods and Lambdas – C# Tutorial | A Complete Guide
- Abstraction in C# Tutorial – Learn the Abstract class and Interface
- Game Development using Unity 3D Tutorial | Ultimate Guide to Learn [UPDATED]
- C++ Reference Tutorial | A Comprehensive Guide for Beginners
- PHP vs Python | Which Is Better For Web Development
- C++ Constructors Tutorial: Types and Copy Constructors
- JavaScript Arrays Tutorial | Complete Beginner’s Guide
- What Is Maven | Maven Tutorial For Beginners
- Spring Tutorial | Perfect Guide for Beginners
- React Hooks Tutorial for Beginners | Ultimate Guide to Learn
- Python for Data Science Tutorial | Quickstart : A Complete Guide
- What is Golang? : A tutorial for beginners | Get started
- Hibernate Validator Tutorial | Learn in 1 Day FREE
- Postman Tutorial for Beginners: API Testing using Postman | A Complete Guide
- Akka Tutorial
- J2EE | Web Development Tutorial for Beginners
- Scala Exception Handling Tutorial | Learn in 1 Day [ STEP-IN ]
- Web development Tutorial
- Visual Studio Tutorial
- PyGame Tutorial
- Python Anaconda Tutorial
- Python Scikit-Learn Cheat Sheet Tutorial
- Mean Stack Tutorial
- Python Requests Tutorial
- Advanced Java Tutorial
- Spring Boot Microservices Tutorial
- Java Servlets Tutorial
- How to Install Pycharm
- Pycharm Tutorial
- Python Version Tutorial
- Python strings
- How to Download Python
- C Data Types Tutorial
- arrays in python
- Python While Loop Tutorial
- JAVA Tutorial
- Loops In C Tutorial
- Java File I/O Tutorial
- Variables in Python Tutorial
- Python Tutorial
- Python Pandas Cheat Sheet Tutorial
- Data Structures Cheat Sheet with Python Tutorial
- Python Tuples Tutorial
- Python If Else Statements Tutorial
- Python Functions Tutorial
- HTML Comments Tutorial | Convert Comments into HTML Codes
- Data Structure and Algorithms Tutorial | Ultimate Guide to Learn
- Gradle Tutorial | For Beginners [ STEP-IN ]
- Encapsulation In Java | Complete Tutorial With Examples
- What is Release Management? | A Comprehensive Tutorial for Beginners
- OOPs Concepts in Java | Learn from Basics with Examples
- The Top Basic Tools of Quality Tutorial | The Ultimate Guide
- Set Environment for C# – Learn How to Setup through this Tutorial
- C# Vs Java Tutorial | Overview and Key Difference
- List of IDEs to run C# Programs | Tutorial for Learning Path
- C Sharp Variables and Constants | The Ultimate Guide
- Unsafe Code in C-Sharp Tutorial | Everything You Need to Know
- Type Conversion Method in C# | A Complete Tutorial
- What Is Synchronization in c# Tutorial | The BEST Step-By-Step Guide
- Understanding Structures in C# | Learn in 1 Day FREE Tutorial
- Strings – C# Tutorial | A Definitive Programming Guide
- Static Keyword in C# Tutorial | Learn with Examples
- Stack Collection in C# Tutorial | A Definitive Guide for Beginners
- C# Sorted List Tutorial with Examples | Learn in 1 Day FREE
- C# Serialization Tutorial | Ultimate Guide to Learn [BEST & NEW]
- Regular Expression in C# Tutorial | Everything You Need to Know
- What is Reflection in C#? | Learn Now Tutorial
- Queue Collection in C# Tutorial | A Definitive Guide
- Properties in C# | The complete Tutorial
- C# Preprocessor Directives Tutorial | Learn in 1 Day FREE
- Polymorphism C# Tutorial | The Ultimate Guide
- C# Operators Tutorial | Learn Arithmetic, Comparison, Logical Concepts
- Namespaces – The complete C# Tutorial
- Multithreading in C# Tutorial | Learn With Examples and Advantages
- Methods – C# Tutorial | A Complete Programming Guide
- Linked List Implementation in C# Tutorial | Ultimate Guide to Learn [UPDATED]
- Introduction to C# Tutorial | Guide for Beginners
- What is Interface in C# | A Defined Free Tutorial
- C# Inheritance Tutorial | A Complete Free Tutorial
- Indexers in C# Tutorial | A Complete Programming Guide
- HashSet Collection in C# Tutorial | Complete Guide Tutorial For Free
- Generics in C# Tutorial | Learn Generic Classes and Methods
- Creating Your First C# Program Tutorial | Learn in 1 Day
- Basics of File Handling in C# Tutorial | The Ultimate Guide
- C# Exception Handling Tutorial | Learn with Best Practices
- Events – C# Tutorial | A Complete Programming Guide
- C# Enumerations Type Tutorial | Learn Everything about Enum
- Dictionary Collection in C# | Ultimate Guide to Learn [NEW & UPDATED]
- Delegates – C# Programming Guide | The Ultimate Guide for Beginners
- Understanding Decision Making Statements in C# | Learn Now Tutorial
- Classes and Objects – C# Fundamentals Tutorial
- C# BitArray Collection Tutorial | Learn in 1 Day FREE
- Attributes in C# Tutorial | Learn to work with attributes in C#
- C# Array Tutorial | Create, Declare, Initialize
- ArrayList Collection on in C# | A Complete tutorial For Beginners
- Anonymous Methods and Lambdas – C# Tutorial | A Complete Guide
- Abstraction in C# Tutorial – Learn the Abstract class and Interface
- Game Development using Unity 3D Tutorial | Ultimate Guide to Learn [UPDATED]
- C++ Reference Tutorial | A Comprehensive Guide for Beginners
- PHP vs Python | Which Is Better For Web Development
- C++ Constructors Tutorial: Types and Copy Constructors
- JavaScript Arrays Tutorial | Complete Beginner’s Guide
- What Is Maven | Maven Tutorial For Beginners
- Spring Tutorial | Perfect Guide for Beginners
- React Hooks Tutorial for Beginners | Ultimate Guide to Learn
- Python for Data Science Tutorial | Quickstart : A Complete Guide
- What is Golang? : A tutorial for beginners | Get started
- Hibernate Validator Tutorial | Learn in 1 Day FREE
- Postman Tutorial for Beginners: API Testing using Postman | A Complete Guide
- Akka Tutorial
- J2EE | Web Development Tutorial for Beginners
- Scala Exception Handling Tutorial | Learn in 1 Day [ STEP-IN ]
- Web development Tutorial
- Visual Studio Tutorial
- PyGame Tutorial
- Python Anaconda Tutorial
- Python Scikit-Learn Cheat Sheet Tutorial
- Mean Stack Tutorial
- Python Requests Tutorial
- Advanced Java Tutorial
- Spring Boot Microservices Tutorial
- Java Servlets Tutorial
- How to Install Pycharm
- Pycharm Tutorial
- Python Version Tutorial
- Python strings
- How to Download Python
- C Data Types Tutorial
- arrays in python
- Python While Loop Tutorial
- JAVA Tutorial
- Loops In C Tutorial
- Java File I/O Tutorial
- Variables in Python Tutorial
- Python Tutorial
- Python Pandas Cheat Sheet Tutorial
- Data Structures Cheat Sheet with Python Tutorial
- Python Tuples Tutorial
- Python If Else Statements Tutorial
- Python Functions Tutorial
arrays in python
Last updated on 10th Oct 2020, Blog, Software Engineering, Tutorials
In programming, an array is a homogenous (belonging to the same data type) collection of elements. Unlike languages like C++, Java, and JavaScript, arrays aren’t among the built-in Python data structures.
Although Python doesn’t have built-in support for arrays, that doesn’t stop programmers from implementing them.
Subscribe For Free Demo
Error: Contact form not found.
What are Python Arrays?
As a replacement to arrays, Python has lists. Nonetheless, Python supports arrays of numeric values using the array module.
When creating arrays using the array module in Python, remember that all elements of the array must be of the same type. If this is not the case then an error will be produced. For instance,
a = [1, 22, 240] is valid
but
a = [1, 22, 240, “Akhil”] is not valid and will thus, yield an error
How does Array Work in Python?
The array is stored in contiguous memory locations, where the index is a sequence of numbers that represents the values stored at every particular index. To access or refer the value at a particular index in an array we make use of a set of square brackets [ ], also we can use the for-in loop to iterate through the array. Array has indices (plural form of an index) and values. At each index, a value is stored. Why we use arrays is because it is difficult to store and remember hundred of numbers at a time, it would be simpler and easier to use arrays in that case, say the integer array is like the following. array (‘i’, [1, 2 , 3, 4 , 5, 6, 7, 8, 9,10] ) then to access these values we will use the following format.
a[0] => 1
a[1] => 2
a[2] => 3
a[3] => 4
a[4] => 5
a[5] => 6
a[6] => 7
a[7] => 8
a[8] => 9
a[9] => 10
Remember, the index starts at 0. We will use a for-in loop also to loop through the given array:
for i in a
print a[i]
Which will give us the values from 1 to 10.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
As per the above illustration, following are the important points to be considered.
- Index starts with 0.
- Array length is 10 which means it can store 10 elements.
- Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.
Length of an Array
The len() method returns the length of an array i.e. the number of elements in an array.
Example
Return the number of elements in the phones array:
- x = len(phones)
Creating Arrays/ How to Declare Arrays in Python
Before declaring arrays, it is required to import the array module. For instance, take a look at the following code snippet:
- import array as ar1
- a = ar1.array(‘d’, [1.2, 2.2, 2.4, 4.6])
- print (a)
Output:
array(‘d’, [1.2, 2.2, 2.4, 4.6])
We’ve created an array of float type after importing the array module. The letter ‘d’ is a type code that determines the type of array during creation. Following are some of the most important array type codes in Python:
- ‘b’ – signed char
- ‘B’ – unsigned char
- ‘d’ – double
- ‘f’ – float
- ‘h’ – signed short
- ‘H’ – unsigned short
- ‘i’ – signed int
- ‘I’ – unsigned int
- ‘l’ – signed long
- ‘L’ – unsigned long
Accessing Array Elements in Python
Indices are used for accessing elements of an array in Python. Like lists, the index starts from 0. For example:
- import array as ar1
- a = ar1.array (‘i’, [22, 24, 46, 53])
- print(“The first element of the array:”, a[0])
- print(“The second element of the array:”, a[1])
- print(“The last element of the array:”, a[2])
Output:
The first element of the array: 22
The second element of the array: 24
The last element of the array: 53
Slicing Arrays in Python
By using the slicing operator (:), it is possible to access a range of elements present in an array in Python programming language. Following code snippet demonstrates using the slicing operator with an array in Python:
- import array as ar1
- number_list = [2, 4, 22, 25, 24, 52, 46, 5]
- number_array = ar1.array(‘i’, number_list)
- print(numbers_array[2:5]) # third to fifth
- print(numbers_array[:-5]) # beginning to forth
- print(numbers_array[5:]) # sixth to end
- print(numbers_array[:]) # beginning to end
Output:
array(‘i’, [22, 25, 24])
array(‘i’, [2, 4, 22, 25])
array(‘i’, [46, 5])
array(‘i’, [2, 4, 22, 25, 24, 52, 46, 5])
Adding or Changing Elements
Arrays are mutable. Hence, their elements can be changed in a similar way as lists. Consider the following code sample:
- import array as ar1
- numbers = ar1.array(‘i’, [1, 2, 3, 4, 6, 10])
- numbers[0] = 0 # replacing the first element 1 with 0
- print(numbers)
- numbers[2:5] = arr.array(‘i’, [4, 6, 8]) # changing third,
Output:
array(‘i’, [0, 2, 3, 4, 6, 10])
array(‘i’, [0, 2, 4, 6, 8, 10])
The append() method is used for adding one element to an array while the extend() method allows adding multiple elements. These new elements are added to the end of the array. Observe the following code snippet:
- import array as ar1
- numbers = ar1.array(‘i’, [1, 2, 3])
- numbers.append(4) # adds 4 to the array at the last position
- print(numbers)
- numbers.extend([5, 6, 7]) # appends iterable to the end of the array
- print(numbers)
Output:
array(‘i’, [1, 2, 3, 4])
array(‘i’, [1, 2, 3, 4, 5, 6, 7])
The concatenation operator (+) is used for concatenating two arrays in Python programming language. For example:
- import array as ar1
- odd = ar1.array(‘i’, [11, 33, 55])
- even = ar1.array(‘i’, [22, 44, 66])
- numbers = ar1.array(‘i’) # creates an empty array of integer
- numbers = odd + even
- print(numbers)
Output:
array(‘i’, [11, 22, 33, 44, 55, 66])
Deleting Elements from an Array
The del statement can be used for removing one or more elements from an array in Python. For instance:
- import array as ar1
- number = ar1.array(‘i’, [11, 22, 33, 33, 44])
- del number[2] # removes the third element
- print(number)
- del number # deletes the entire array
- print(number)
Output:
array(‘i’, [11, 22, 33, 44])
Error: array is not defined
While the remove() method can be used for removing a specific element from the array, the pop() method allows for removing a specific element and display it. Use of both these methods are illustrated in the following code snippet:
- import array as ar1
- numbers = ar1.array(‘i’, [10, 11, 12, 12, 13])
- numbers.remove(12)
- print(numbers)
- print(numbers.pop(2))
- print(numbers)
Output:
array(‘i’, [10, 11, 12, 13])
12
array(‘i’, [10, 11, 13])
Searching an Element in Array
Based on the index or value of the element, it is possible to search for the same in an array. The index() method is used for searching an element in an array based on its value. The method returns the index of the element being searched. For instance:
- import array as ar1
- numbers = ar1.array(‘i’, [10,20,30,40,50])
- print (array1.index(40)) # returns the index of the element 40
Output:
3
In case there is no such element that is being searched in an array, the program will give out an error.
Array Methods
These are the various inbuilt methods in Python for using with arrays:
- append() – Adds an element at the end of the array list
- clear() – Eliminates all elements from the array list
- copy() – Returns a copy of the array list
- count() – Returns the elements along with their total number
- extend() – Add the elements of an array list to the end of the current list
- index() – Returns the index of the first element in an array list with the specified value
- insert() – Adds an element to the specified position in the array list
- pop() – Removes an element from the specified position
- remove() – Eliminates the first element with the specified value
- reverse() – Reverses the order of an array list
- sort() – Sorts the array list
Advantages of using an Array
- Arrays can handle very large datasets efficiently
- Computationally-memory efficient
- Faster calculations and analysis than lists
- Diverse functionality (many functions in Python packages). With several Python packages that make trend modeling, statistics, and visualization easier.
Conclusion
Although knowing how to deal with arrays isn’t a mandatory part of learning Python, able to do so is surely an added advantage. This is especially true when dealing with churning out arrays and matrices. Nonetheless, lists in Python are way much more flexible than arrays.
Unlike arrays, lists are able to store elements belonging to different data types and are faster. Typically, the array module is required for interfacing with C code. It is typically advised to avoid using arrays in Python. However, that doesn’t mean that you can’t learn them.