{"id":2532,"date":"2023-10-18T16:48:45","date_gmt":"2023-10-18T11:18:45","guid":{"rendered":"https:\/\/python-programs.com\/?p=2532"},"modified":"2023-11-10T11:47:06","modified_gmt":"2023-11-10T06:17:06","slug":"how-to-create-and-initialize-a-list-of-lists-in-python","status":"publish","type":"post","link":"https:\/\/python-programs.com\/how-to-create-and-initialize-a-list-of-lists-in-python\/","title":{"rendered":"How to Create and Initialize a List of Lists in Python?"},"content":{"rendered":"

Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.<\/p>\n

In Python, a list of lists is a list object with each list element being a separate list.<\/p>\n

Given the size,<\/p>\n

The task is to create and Initialize a list of lists\u00a0 of given size in Python using different methods.<\/p>\n

Examples:<\/strong><\/p>\n

Input : <\/strong><\/p>\n

Size=4\r\n<\/pre>\n

Output :<\/strong><\/p>\n

[ [ ] , [ ] , [ ] , [ ] ]<\/pre>\n

Creating list of lists with the same ID(Not Preferable):<\/h2>\n

Below is the fastest way to build and initialize a list of lists with the same ID.<\/p>\n

# Let us take size as 4\r\nlistoflists = [[]]*4 \r\n# print the listoflists \r\nprint(\"List of Lists : \", listoflists) \r\n# Print the ID's of all elements in this listoflists \r\nprint(\"ID's : \") \r\nfor element in listoflists: \r\n    print(id(element))<\/pre>\n

Output:<\/strong><\/p>\n

List of Lists :  [[], [], [], []]\r\nID's : \r\n140398466447368\r\n140398466447368\r\n140398466447368\r\n140398466447368<\/pre>\n

Explanation:<\/strong><\/p>\n

Here List of Lists of size 4 is created but we can see all are having same Id. This will result in the list containing the same list object repeated N times and cause referencing errors.<\/p>\n

Creating list of lists with the different ID’s:<\/h3>\n

It is most preferable because all the lists will have different ID’s such that we can access and refer them separately.<\/p>\n

There are several ways to create list of lists some of them are:<\/p>\n