How to get the First and Last Element of a List in python with example

The list contains elements or a list of sub-lists or a Map i.e two dimensions list.

Flatten list is to output a single list from a two-dimension list.

Let’s create a list of sub-list or two-dimensional lists in python.

list = [[1, 2], [3],[4,5,6],[7],[8,9,10]]

A two-dimensional list contains a list of elements, where each element is again a list.

After flatting the list, the result is

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let’s see multiple ways to flatten a list in Python

Python Flatten List examples

  • use nested for in loops

List elements can be iterated using for in loop.

Use nested for in loop and append to the empty list using the append method.

list = [[1, 2], [3],[4,5,6],[7],[8,9,10]]

print(list)
flattenlist = []
for childlist in list:
for value in childlist:
flattenlist.append(value)
print(flattenlist)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • use the itertools chain method itertools class contains the chain method that iterates the list and passes it to the list constructor Here is a syntax
itertools.chain(\*iterables)

Here is an example

import itertools

numbers = [[1, 2], [3],[4,5,6],[7],[8,9,10]]
flattenlist = list(itertools.chain(*numbers))

print(flattenlist)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • use reduce functions from functools functools provides reduce function which appends the next element with an accumulated list. Here is an example
from functools import reduce
numbers = [[1, 2], [3],[4,5,6],[7],[8,9,10]]

print(numbers)
flattenlist =  reduce(lambda next, flatten: next + flatten, numbers)
print(flattenlist)

Output:

[[1, 2], [3], [4, 5, 6], [7], [8, 9, 10]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

iteration_utilities flatten method

flatten method in the iteration_utilities class convert list of sublist to single dimensional list.

Here is an example

from iteration_utilities import flatten
numbers = [[1, 2], [3],[4,5,6],[7],[8,9,10]]

print(numbers)
flattenlist = list(flatten(numbers))
print(flattenlist)