Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Monday, February 3, 2020

Make a flat list out of list of lists in django

Lists

Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence of values, then, it provides the ‘list’ class. A Python list can be seen as a collection of values.

To create a python list of items, you need to mention the items, separated by commas, in square brackets. This is the python syntax you need to follow. Then assign it to a variable. Remember once again, you don’t need to declare the data type, because Python is dynamically-typed.

  1. >>> colors=['red','green','blue']

flat list out of list of lists


Combining a list of lists to a single list is called a flat list.


[[1,2,3], [4,5], [6]] => [1, 2, 3, 4, 5, 6]

Django

Django provides a method called flatten for this purpose. This will flatten the list directly thereby saving us a lot of time and code.




#Happy coding

No comments:

Post a Comment