How to create a List (or Array) inside the another List (or Array)?
Last Updated :
23 Mar, 2024
A list is a collection of similar or different types of data elements.
Dynamic Language like python can store different data types in the same list, but for statically typed language like C++, a list means a collection of similar data types. Every list item can be accessed by its indices, and for most of the languages (python, java, C++, etc.) indices start from 0.
An array is the same as the list for dynamic language, but for a language like C++ where for a list dynamic memory allocation is done by the compiler, for array user has to do it manually.
Implementation of List inside List using C++:
C++
// C++ code to create a list inside another list
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Inside this list the another list
// will be created/inserted.
// Also ListofList only can store
// vector<int> datatype, unlike
// python which can store anything.
list<list<int> > ListofList;
// The list to be inserted,
// normal integer type list.
list<int> insertedList;
for (int i = 1; i < 5; i++) {
insertedList.push_back(i);
}
// Pushing insertedList inside ListofList
ListofList.push_back(insertedList);
ListofList.push_back(insertedList);
for (auto it = ListofList.begin();
it != ListofList.end(); it++) {
for (int j : *it)
cout << j << " ";
cout << endl;
}
return 0;
}
Java
// Java code to create a list inside another list
import java.util.*;
class GFG{
public static void main(String[] args)
{
// Inside this list the another list
// will be created/inserted.
// Also ListofList only can store
// Vector<Integer> datatype, unlike
// Java which can store anything.
ArrayList<ArrayList<Integer> > ListofList = new ArrayList<ArrayList<Integer> >();
// The list to be inserted,
// normal integer type list.
ArrayList<Integer> insertedList = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
insertedList.add(i);
}
// Pushing insertedList inside ListofList
ListofList.add(insertedList);
ListofList.add(insertedList);
for (ArrayList<Integer> it : ListofList){
for (int j : it)
System.out.print(j+ " ");
System.out.println();
}
}
}
// This code is contributed by shikhasingrajput
C#
// C# code to create a list inside another list
using System;
using System.Collections.Generic;
public class GFG{
public static void Main(String[] args)
{
// Inside this list the another list
// will be created/inserted.
// Also ListofList only can store
// List<int> datatype, unlike
// C# which can store anything.
List<List<int> > ListofList = new List<List<int> >();
// The list to be inserted,
// normal integer type list.
List<int> insertedList = new List<int>();
for (int i = 1; i < 5; i++) {
insertedList.Add(i);
}
// Pushing insertedList inside ListofList
ListofList.Add(insertedList);
ListofList.Add(insertedList);
foreach (List<int> it in ListofList){
foreach (int j in it)
Console.Write(j+ " ");
Console.WriteLine();
}
}
}
// This code is contributed by shikhasingrajput
JavaScript
// JavaScript code to create a list inside another list
// Define ListofList using arrays (JavaScript does not have a built-in list type)
const ListofList = [];
// The list to be inserted, a normal integer type list.
const insertedList = [];
// Populate the insertedList
for (let i = 1; i < 5; i++) {
insertedList.push(i);
}
// Pushing insertedList inside ListofList
ListofList.push(insertedList.slice()); // Using slice to create a copy of the array
ListofList.push(insertedList.slice());
// Display the elements of ListofList
for (const sublist of ListofList) {
for (const element of sublist) {
console.log(element + " ");
}
console.log();
}
// This code is contributed by Yash Agarwal(yashagarwal2852002)
Python3
# Python code to create a list inside another list
# Inside this list, another list will be created/inserted.
# Also, ListofList can only store lists of integers,
# unlike Python which can store any type of object.
ListofList = []
# The list to be inserted, a normal integer type list.
insertedList = [i for i in range(1, 5)]
# Pushing insertedList inside ListofList
ListofList.append(insertedList.copy())
ListofList.append(insertedList.copy())
# Loop through ListofList and print each inner list
for innerList in ListofList:
for element in innerList:
print(element, end=" ")
print()
Implementation of List inside List using Python:
For Dynamic Language like python Create 2 or more lists and append them inside one of the lists, And it'll create a list inside a list,
C++
#include <iostream>
#include <vector>
int main() {
// Declare and initialize the lists
std::vector<int> list_1 = {1, 2, 3, 4};
std::vector<int> list_2 = {4, 7, 8, 9};
std::vector<int> list_3 = {3, 1, 4, 7};
std::vector<int> list_4 = {3, 5, 7, 11};
// Append elements of list_2, list_3, and list_4 to list_1
list_1.insert(list_1.end(), list_2.begin(), list_2.end());
list_1.insert(list_1.end(), list_3.begin(), list_3.end());
list_1.insert(list_1.end(), list_4.begin(), list_4.end());
// Print the combined list_1
for (const auto& elem : list_1) {
std::cout << elem << " ";
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Initialize a List<Object> named list1 with initial values.
List<Object> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
// Initialize three lists of integers: list2, list3, and list4.
List<Integer> list2 = new ArrayList<>(Arrays.asList(4, 7, 8, 9));
List<Integer> list3 = new ArrayList<>(Arrays.asList(3, 1, 4, 7));
List<Integer> list4 = new ArrayList<>(Arrays.asList(3, 5, 7, 11));
// Add the integer lists (list2, list3, list4) to the main list (list1).
list1.add(list2);
list1.add(list3);
list1.add(list4);
// Output the main list in a readable format.
System.out.print("[");
for (int i = 0; i < list1.size(); i++) {
Object item = list1.get(i);
if (item instanceof List) {
// If the item is a List<Integer>, format it as "[item1, item2, ...]".
List<Integer> sublist = (List<Integer>) item;
System.out.print("[" + String.join(", ", sublist.stream().map(Object::toString).toArray(String[]::new)) + "]");
} else {
System.out.print(item);
}
// Add a comma and space if the current item is not the last one.
if (i != list1.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Initialize a List<object> named list1 with initial values.
List<object> list1 = new List<object> { 1, 2, 3, 4 };
// Initialize three lists of integers: list2, list3, and list4.
List<int> list2 = new List<int> { 4, 7, 8, 9 };
List<int> list3 = new List<int> { 3, 1, 4, 7 };
List<int> list4 = new List<int> { 3, 5, 7, 11 };
// Add the integer lists (list2, list3, list4) to the main list (list1).
list1.Add(list2);
list1.Add(list3);
list1.Add(list4);
// Output the main list in a readable format.
Console.Write("[");
foreach (var item in list1){
if (item is List<int>){
// If the item is a List<int>, format it as "[item1, item2, ...]".
List<int> sublist = item as List<int>;
Console.Write("[" + string.Join(", ", sublist) + "]");
}
else Console.Write(item + "");
// Add a comma and space if the current item is not the last one.
if (item != list1.Last()) Console.Write(", ");
}
Console.Write("]\n");
}
}
JavaScript
<script>
// JavaScript code to create a list inside another list
let list_1 = [1, 2, 3, 4];
let list_2 = [4, 7, 8, 9];
let list_3 = [3, 1, 4, 7];
let list_4 = [3, 5, 7, 11];
// list_2, list_3 and list_4
// have been appended inside list_1
list_1.push(list_2)
list_1.push(list_3)
list_1.push(list_4)
// As List in python can store different data types,
// that's why here it able to store
// integer type and List in a same list.
document.write(list_1)
// This code is contributed by rakeshsahni
</script>
Python3
list_1 = [1, 2, 3, 4]
list_2 = [4, 7, 8, 9]
list_3 = [3, 1, 4, 7]
list_4 = [3, 5, 7, 11]
# list_2, list_3 and list_4
# have been appended inside list_1
list_1.append(list_2)
list_1.append(list_3)
list_1.append(list_4)
# As List in python can store different data types,
# that's why here it able to store
# integer type and List in a same list.
print(list_1)
Output[1, 2, 3, 4, [4, 7, 8, 9], [3, 1, 4, 7], [3, 5, 7, 11]]
Creating array inside the array in C:
But for statically typed language like C one have to predefine everything like the data type of the array which stores another array.
For example, to create a 1D integer array inside another array, firstly, the main array should store (int*) datatype then only, another 1D array can be stored/created inside that array.
Note: Following the same way an array can be created inside another array in C++ also.
C++
// C++ code to create array inside array
#include <bits/stdc++.h>
using namespace std;
#define size 5
int main()
{
// Here is an array(dynamically allocated)
// that can store array(1-D),
// or (int*) type data
int** out_array = (int**)malloc(size * sizeof(int*));
// Here is an normal integer array
// (dynamically allocated), which stores
// (int) datatype
int* temp1 = (int*)malloc(size * sizeof(int));
int* temp2 = (int*)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) {
temp1[i] = i; // 0, 1, 2, 3, 4
temp2[i] = i;
}
// Now Creating array inside array
// by storing int* datatype
// inside the out_array
out_array[0] = temp1;
out_array[1] = temp2;
cout << "After Creating array inside array " << endl;
// Since there are only two
// array inside the out_array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < size; j++) {
cout << out_array[i][j] << " ";
}
cout << endl;
}
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#define size 5
int main()
{
// Here is an array(dynamically allocated)
// that can store array(1-D), or
// (int*) type datat
int** out_array = (int**)malloc(size * sizeof(int*));
// Here is an normal integer array
// (dynamically allocated), which
// stores (int) datatype
int* temp1 = (int*)malloc(size * sizeof(int));
int* temp2 = (int*)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) {
temp1[i] = i;
temp2[i] = i;
}
// Now Creating array inside array
// by storing int* datatype
// inside the out_array
out_array[0] = temp1;
out_array[1] = temp2;
printf("After Creating array inside array\n");
// Since there are only two arrays
// inside the out_array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < size; j++) {
printf("%d ", out_array[i][j]);
}
printf("\n");
}
return 0;
}
Java
// Java code to create array inside array
class GFG{
static final int size = 5;
public static void main(String[] args)
{
// Here is an array(dynamically allocated)
// that can store array(1-D),
// or (int*) type data
int [][]out_array = new int[size][size];
// Here is an normal integer array
// (dynamically allocated), which stores
// (int) datatype
int []temp1 = new int[size];
int []temp2 = new int[size];
for (int i = 0; i < size; i++) {
temp1[i] = i; // 0, 1, 2, 3, 4
temp2[i] = i;
}
// Now Creating array inside array
// by storing int* datatype
// inside the out_array
out_array[0] = temp1;
out_array[1] = temp2;
System.out.print("After Creating array inside array " +"\n");
// Since there are only two
// array inside the out_array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < size; j++) {
System.out.print(out_array[i][j]+ " ");
}
System.out.println();
}
}
}
// This code is contributed by shikhasingrajput
Python
# Define the size of the array
size = 5
# Create a list to store arrays (2D array)
out_array = []
# Create two separate arrays (1D arrays)
temp1 = range(size)
temp2 = range(size)
# Append the arrays to the list to create a 2D array
out_array.append(temp1)
out_array.append(temp2)
print "After Creating array inside array"
# Iterate through the 2D array and print its elements
for i in range(len(out_array)):
for j in range(size):
print out_array[i][j],
print
C#
using System;
class Program {
static void Main(string[] args)
{
const int size = 5;
// Here is an array(dynamically allocated)
// that can store array(1-D),
// or (int[]) type data
int[][] outArray = new int[size][];
// Here is a normal integer array
// (dynamically allocated), which stores
// (int) datatype
int[] temp1 = new int[size];
int[] temp2 = new int[size];
for (int i = 0; i < size; i++) {
temp1[i] = i; // 0, 1, 2, 3, 4
temp2[i] = i;
}
// Now Creating array inside array
// by storing int[] datatype
// inside the outArray
outArray[0] = temp1;
outArray[1] = temp2;
Console.WriteLine(
"After Creating array inside array:");
// Since there are only two
// arrays inside the outArray
for (int i = 0; i < 2; i++) {
for (int j = 0; j < size; j++) {
Console.Write(outArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// Size of the array
const size = 5;
// Here is an array (dynamically allocated)
// that can store arrays (1-D),
// or (int[]) type data
const out_array = new Array(size);
// Here are normal integer arrays
// (dynamically allocated), which store
// (number) datatype
const temp1 = new Array(size);
const temp2 = new Array(size);
for (let i = 0; i < size; i++) {
temp1[i] = i; // 0, 1, 2, 3, 4
temp2[i] = i;
}
// Now creating array inside array
// by storing arrays (int[]) datatype
// inside the out_array
out_array[0] = temp1;
out_array[1] = temp2;
console.log("After creating array inside array: ");
// Since there are only two
// arrays inside the out_array
for (let i = 0; i < 2; i++) {
let output = "";
for (let j = 0; j < size; j++) {
output += out_array[i][j] + " ";
}
console.log(output);
}
OutputAfter Creating array inside array
0 1 2 3 4
0 1 2 3 4
Similar Reads
How to Create an Array of Object Literals in a Loop using JavaScript?
Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript. Here are different app
5 min read
How to create an array in R
The array is the fundamental data structure in R used to store multiple elements of the same data type. In this article, we will explore two different approaches to creating an array in R Programming Language. Creating an array in RBelow are the approaches for creating an array in R. Using array() f
4 min read
Copy Array Items Into Another Array in JavaScript
In JavaScript, copying array items into another array in JavaScript is helpful when you want to make changes to the data without affecting the original array. It helps avoid mistakes, keeps the original data safe, and is useful when you need to work with a separate copy of the array for testing or p
5 min read
How to Store an Object Inside an Array in JavaScript ?
Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 min read
How to Insert a New Element in an Array in PHP ?
In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.We can insert an element or item in an array using the below function
5 min read
Extend existing JS array with Another Array
To extend an array with another without creating a new array we can use the JavaScript array.push() method. This method extend the array by adding the elements at the end. These are the following methods: 1. Using array.push() with Spread operator JavaScript array.push() method adds one or more elem
2 min read
What is nesting of list & how to create the nested list in HTML ?
Nesting of lists in HTML involves placing one list within another list item, creating a hierarchical structure. This is done by embedding a <ul> (unordered) or <ol> (ordered) list inside an <li> (list item) element. The proper way to make a nested HTML list is to use the <ul>
3 min read
How to create a list in R
In this article, we will discuss What is a list and various methods to create a list using R Programming Language. What is a list?A list is the one-dimensional heterogeneous data i.e., which stores the data of various types such as integers, float, strings, logical values, and characters. These list
2 min read
How to pass an array to a function in Python
In this article, we will discuss how an array or list can be passed to a function as a parameter in Python. Pass an array to a function in Python So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is
4 min read
Why use an Array to implement a "list" instead of a Hash Table?
What is an Array?An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. Array C++ #include <iostream> using namespace std; // driver program int
4 min read