Posts

Showing posts with the label list

Convert Nested List To Flat List

Image
  Code Suppose you have a list like : [[1], [2,3], [4, [5, 6]], [7], [8], [9], [10]] Now if I want to make it a flat list like : [1,2,3,4,5,6,7,8,9] How can we do that?  😕  Don't worry dear, there are many ways to do so. You are going to take help one builtin lib of python 😍 # Example from functools import reduce >>> l = [[1], [2,3], [4, 5, 6], [7], [8], [9], [10]] >>> flat_list = reduce(lambda x, y: x+y, l) >>> flat_list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Enjoy Edge-cutting Technology 😉 Get Help

List comprehension in Python

Image
Code Example 1: l = [i for i in range(1, 11, 1)] print(l) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Example 2: l = [[i, i+1] for i in range(1,6)] print(l) Output: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] Example 3: l = [i for i in range(1, 11, 1)] print(l) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Example 4: l = [i for i in range(1,6) if i%2 == 0] print(l) Output: [2, 4] Get Help

List Data Type in Python

Image
Concept List  is a collection which is mutable, ordered and changeable. Allows duplicate members. List are just like the arrays, declared in other languages. List can contain int, float, str, list, dict, set any data type. Code Example Example 1: # empty list >>> l = [] [] Example 2: >>> l = [10, 20.35, 'Hello'] [10, 20.35, 'Hello'] Example 3: >>> l = [10, 20.35, 'Hello'] >>> len(l) 3 >>> l [1] 20.35 # append >>>  l.append("New") [10, 20.35, 'Hello', 'New'] >>  l [1: 3] [20.35, 'Hello'] >>> l [-3, -1] 20.35, 'Hello'] >>> l [0] = 40 >>> l [40, 20.35, 'Hello', 'New'] #  reverse >>> l.reverse() >>> l ['New', 'Hello', 20.35, 40] #  extend >>> l = ['New', 'Hello', 20.35, 10] >>> l1 = ['a', 'b'] >>> l.extend(l1) >>> l ['N...