What is the difference between lists and arrays?
Last Updated :
06 Feb, 2024
In programming, lists and arrays are data structures used to organize and store data. Both have their unique features and purposes. Lists are dynamic and flexible, allowing for easy resizing during runtime, while arrays are static with a fixed size. This difference impacts memory usage and performance.
What are Lists?
Lists are a versatile data structure in programming, designed to hold a collection of elements with the flexibility to handle different data types. Unlike arrays, lists are dynamic, meaning their size can change during the execution of a program. This adaptability makes lists particularly useful for tasks involving the addition or removal of elements. Lists provide a convenient interface for developers to manage and organize data, allowing for efficient operations such as appending, inserting, or deleting elements. The ability to dynamically adjust their size makes lists a powerful tool for handling varying amounts of data in a program.
What are Arrays?
Arrays are a fundamental data structure in programming that allows you to store a collection of elements of the same data type in a contiguous block of memory. Each element in the array is identified by an index, representing its position. The key characteristic of arrays is that they offer quick and direct access to elements using these indices. They provide a systematic way to organize and manage data, making it efficient to retrieve, modify, and manipulate information stored in the array. Arrays are widely used in various programming languages for their simplicity and effectiveness in handling ordered sets of data.
Difference Between Lists and Arrays:
|
Arrays have a fixed size set during creation.
| Lists are dynamic and can change in size during runtime.
|
All elements in an array must be of the same data type.
| Lists can accommodate elements of different data types.
|
Memory for the entire array is allocated at once during initialization.
| Lists dynamically allocate memory as elements are added or removed.
|
Arrays provide constant-time access to elements through indexing.
| Lists may have slightly variable access time due to dynamic resizing.
|
Arrays are less flexible as their size cannot be easily changed.
| Lists are more flexible, allowing easy addition or removal of elements.
|
May lead to memory wastage if size is larger than necessary.
| More memory-efficient due to dynamic allocation.
|
Common in languages like C/C++.
| Common in languages like Python and Java.
|
Implementation of Lists:
In the provided code example in Python, a list is initialized to store integers (10, 20, 30). Elements are added, accessed by index, modified, and removed. In Python, the append method is used for addition and remove for deletion. The example demonstrates the fundamental operations of creating, modifying, and managing lists in these programming languages.
C++
#include <iostream>
#include <vector>
int main() {
// Creating an empty vector
std::vector<int> myArray;
// Adding elements to the vector
myArray.push_back(10);
myArray.push_back(20);
myArray.push_back(30);
// Displaying the elements in the vector
std::cout << "Elements in the vector: ";
for (int num : myArray) {
std::cout << num << " ";
}
std::cout << std::endl;
// Accessing elements by index
int firstElement = myArray[0];
int secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Removing an element by value
for (auto it = myArray.begin(); it != myArray.end(); ++it) {
if (*it == 30) {
myArray.erase(it);
break;
}
}
// Displaying the updated vector
std::cout << "Updated vector: ";
for (int num : myArray) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
// This code is contributed by shivamgupta0987654321
Java
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args)
{
// Creating an empty ArrayList
ArrayList<Integer> myArray = new ArrayList<>();
// Adding elements to the ArrayList
myArray.add(10);
myArray.add(20);
myArray.add(30);
// Displaying the elements in the ArrayList
System.out.print("Elements in the ArrayList: ");
for (int num : myArray) {
System.out.print(num + " ");
}
System.out.println();
// Accessing elements by index
int firstElement = myArray.get(0);
int secondElement = myArray.get(1);
// Modifying an element
myArray.set(1, 25);
// Removing an element by value
Iterator<Integer> iterator = myArray.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
if (element == 30) {
iterator.remove();
break;
}
}
// Displaying the updated ArrayList
System.out.print("Updated ArrayList: ");
for (int num : myArray) {
System.out.print(num + " ");
}
System.out.println();
}
}
Python3
# Creating an empty list
my_list = []
# Adding elements to the list
my_list.append(10)
my_list.append(20)
my_list.append(30)
# Displaying the elements in the list
print("Elements in the list:", my_list)
# Accessing elements by index
first_element = my_list[0]
second_element = my_list[1]
# Modifying an element
my_list[1] = 25
# Removing an element
my_list.remove(30)
# Displaying the updated list
print("Updated list:", my_list)
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating an empty list
List<int> myArray = new List<int>();
// Adding elements to the list
myArray.Add(10);
myArray.Add(20);
myArray.Add(30);
// Displaying the elements in the list
Console.Write("Elements in the list: ");
foreach (int num in myArray)
{
Console.Write(num + " ");
}
Console.WriteLine();
// Accessing elements by index
int firstElement = myArray[0];
int secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Removing an element by value
for (int i = 0; i < myArray.Count; ++i)
{
if (myArray[i] == 30)
{
myArray.RemoveAt(i);
break;
}
}
// Displaying the updated list
Console.Write("Updated list: ");
foreach (int num in myArray)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
JavaScript
// Creating an empty array
let myArray = [];
// Adding elements to the array
myArray.push(10);
myArray.push(20);
myArray.push(30);
// Displaying the elements in the array
console.log("Elements in the array:", myArray);
// Accessing elements by index
let firstElement = myArray[0];
let secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Removing an element (in this case, removing by value)
let indexToRemove = myArray.indexOf(30);
if (indexToRemove !== -1) {
myArray.splice(indexToRemove, 1);
}
// Displaying the updated array
console.log("Updated array:", myArray);
OutputElements in the vector: 10 20 30
Updated vector: 10 25
Implementation of Arrays:
In C++, C, Python, Java, and JavaScript, the code creates an array with elements (10, 20, 30), accesses and modifies elements by index, and displays the updated array. The syntax and specific methods differ across languages, but the fundamental array operations remain consistent, showcasing how to manipulate and iterate through arrays.
C++
#include <iostream>
using namespace std;
int main() {
// Creating an array
int myArray[3] = {10, 20, 30};
// Accessing elements by index
int firstElement = myArray[0];
int secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Displaying the elements in the array
for (int i = 0; i < 3; ++i) {
cout << myArray[i] << " ";
}
return 0;
}
C
#include <stdio.h>
int main() {
// Creating an array
int myArray[3] = {10, 20, 30};
// Accessing elements by index
int firstElement = myArray[0];
int secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Displaying the elements in the array
for (int i = 0; i < 3; ++i) {
printf("%d ", myArray[i]);
}
return 0;
}
Java
public class ArrayExample {
public static void main(String[] args) {
// Creating an array
int[] myArray = {10, 20, 30};
// Accessing elements by index
int firstElement = myArray[0];
int secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Displaying the elements in the array
for (int i = 0; i < 3; ++i) {
System.out.print(myArray[i] + " ");
}
}
}
Python3
# Creating an array (using a list)
my_array = [10, 20, 30]
# Accessing elements by index
first_element = my_array[0]
second_element = my_array[1]
# Modifying an element
my_array[1] = 25
# Displaying the elements in the array
for element in my_array:
print(element, end=" ")
C#
using System;
class Program
{
static void Main()
{
// Creating an array
int[] myArray = { 10, 20, 30 };
// Modifying an element
myArray[1] = 25;
// Displaying the elements in the array
foreach (int element in myArray)
{
Console.Write(element + " ");
}
}
}
JavaScript
// Creating an array
let myArray = [10, 20, 30];
// Accessing elements by index
let firstElement = myArray[0];
let secondElement = myArray[1];
// Modifying an element
myArray[1] = 25;
// Displaying the elements in the array
for (let i = 0; i < myArray.length; ++i) {
console.log(myArray[i]);
}
In conclusion, arrays offer a fixed-size, contiguous memory structure with efficient element access whereas lists provide dynamic sizing, flexibility, and built-in methods for ease of manipulation. The choice between the two depends on the specific requirements of the application, with arrays excelling in scenarios where fixed-size and direct memory access are critical, and lists proving advantageous for dynamic data and diverse operations. Ultimately, understanding the unique features of each data structure enables developers to make informed decisions based on the demands of their programming tasks.
Similar Reads
Swift - Difference Between Sets and Arrays
An array is a linear data structure which has contiguous memory in a single variable that can store N number of elements. For example, if we want to take 10 inputs from the user we canât initialise 10 variables. In this case you can make use of arrays. It can store N number of elements into a single
3 min read
Difference between Stack and Array
Stack: A stack is a linear data structure in which elements can be inserted and deleted only from one side of the list, called the top. A stack follows the LIFO (Last In First Out) principle, i.e., the element inserted at the last is the first element to come out. The insertion of an element into a
3 min read
Difference between ArrayList, LinkedList and Vector
ArrayList:Array List is an implemented class of List interface which is present in package java.util. Array List is created on the basis of the growable or resizable array. And Array List is an index-based data structure. In ArrayList, the element is stored in a contiguous location. It can store dif
11 min read
Difference between Array, Queue and Stack
Array: An Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of
3 min read
Difference between Array and Map
Array:An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of t
12 min read
Difference Between List and Set in Java
The List interface allows storing the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values are allowed to store. List preserves the insertion order, it allows positional access and insertion of elements. Declaration: public abstr
2 min read
Difference between Array and String in Java
An array is a collection of similar type of elements that are stored in a contiguous memory location. Arrays can contain primitives(int, char, etc) as well as object(non-primitives) references of a class depending upon the definition of the array. In the case of primitive data type, the actual value
5 min read
Difference between an array and a tree
Array:An array is a collection of homogeneous(same type) data items stored in contiguous memory locations. For example, if an array is of type âintâ, it can only store integer elements and cannot allow the elements of other types such as double, float, char, etc. The array is a linear data structure
3 min read
Difference between Static Arrays and Dynamic Arrays
In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept. Types of Arrays:There are basicall
5 min read
Difference between a Seq and a List in Scala
Sequences of items are represented in Scala using two different collection types: Seq and List. Nonetheless, there are significant distinctions between them in terms of use, implementation, and mutability. Mutability:Seq: Sequences of items, known as seqs, may be either changeable or immutable. It i
2 min read