Tuesday, 27 August 2024

7 Lesser-Known Python Techniques about Lists

 

1. Flatten a Nested List

Flatten a deeply nested list into a single list of elements.


from collections.abc import Iterable


def flatten(lst):

    for item in lst:

        if isinstance(item, Iterable) and not isinstance(item, str):

            yield from flatten(item)

        else:

            yield item


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

flat_list = list(flatten(nested_list))

print(flat_list)  

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


2. List of Indices for Specific Value

Get all indices of a specific value in a list.


lst = [10, 20, 10, 30, 10, 40]

indices = [i for i, x in enumerate(lst) if x == 10]

print(indices) 

[0, 2, 4]

3. Transpose a List of Lists (Matrix)

Transpose a matrix-like list (switch rows and columns).


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

transposed = list(map(list, zip(*matrix)))

print(transposed)  

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



4. Rotate a List

Rotate the elements of a list by n positions.


def rotate(lst, n):

    return lst[-n:] + lst[:-n]


lst = [1, 2, 3, 4, 5]

rotated_lst = rotate(lst, 2)

print(rotated_lst) 

[4, 5, 1, 2, 3]

5. Find Duplicates in a List

Identify duplicate elements in a list.


from collections import Counter


lst = [1, 2, 2, 3, 4, 4, 4, 5]

duplicates = [item for item, count in Counter(lst).items() if count > 1]

print(duplicates)  

[2, 4]


6. Chunk a List

Split a list into evenly sized chunks.


def chunk(lst, n):

    for i in range(0, len(lst), n):

        yield lst[i:i + n]


lst = [1, 2, 3, 4, 5, 6, 7, 8]

chunks = list(chunk(lst, 3))

print(chunks)  

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

7. Remove Consecutive Duplicates

Remove consecutive duplicates from a list, preserving order.


from itertools import groupby


lst = [1, 2, 2, 3, 3, 3, 4, 4, 5]

result = [key for key, _ in groupby(lst)]

print(result)  

[1, 2, 3, 4, 5]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (21) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses