Open In App

How to create a List (or Array) inside the another List (or Array)?

Improve
Improve
Like Article
Like
Save
Share
Report

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()

Output
1 2 3 4 
1 2 3 4 









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);
}

Output
After Creating array inside array 
0 1 2 3 4 
0 1 2 3 4 











Last Updated : 23 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads