Fundamentals 7 min read

Python Container Types and Handy Tricks for Lists, Dictionaries, and More

This article presents a collection of practical Python techniques for working with built‑in container types such as lists, tuples, sets, and dictionaries, covering operations like extracting maximum values, counting elements, slicing, copying, mapping, filtering, column extraction, and transposition, all illustrated with clear code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Container Types and Handy Tricks for Lists, Dictionaries, and More

Python provides a rich set of container data types, including list, tuple, set, and dict. Below are several useful tricks to write more Pythonic code.

Extract maximum value from a dictionary max(my_dict.values()) Get the key of the maximum value: max(my_dict, key=my_dict.get) Get both the key and value of the maximum entry: max(my_dict.items(), key=lambda x: x[1]) Alternative using operator.itemgetter:

import operator
max(my_dict.items(), key=operator.itemgetter(1))

Count occurrences of each element in a list {x: my_list.count(x) for x in set(my_list)} Or using itertools.groupby:

from itertools import groupby
{key: len(list(group)) for key, group in groupby(sorted(my_list))}

Or using collections.Counter:

from collections import Counter
dict(Counter(my_list))

Truncate a list efficiently

my_list = my_list[:i]
my_list = my_list[j:]

Better approach using del:

del my_list[i:]
del my_list[:j]

Zip operation with the longest iterable list(zip('abc', [1, 2, 3, 4])) Result contains elements up to the shortest iterable. To use the longest iterable, employ itertools.zip_longest:

from itertools import zip_longest
list(zip_longest('abc', [1, 2, 3, 4]))

Copying lists

Shallow copy via slicing: thy_list = my_list[:] Deep copy using copy.deepcopy:

import copy
thy_list = copy.deepcopy(my_list)

Apply a function to multiple iterables with map

my_list = [11, 13, 15, 17]
thy_list = [2, 4, 6, 8, 10]
list(map(lambda x, y: x + y, my_list, thy_list))

Equivalent using list comprehension and zip:

my_list = [11, 13, 15, 17]
thy_list = [2, 4, 6, 8, 10]
[x + y for x, y in zip(my_list, thy_list)]

Remove falsy values (None, 0, empty) from a list list(filter(bool, my_list)) Or using a list comprehension: [x for x in my_list if x] Extract a specific column from a nested list (matrix)

my_list = [
    [1, 1, 2, 2],
    [5, 6, 7, 8],
    [3, 3, 4, 4],
]
col1, *_ = zip(*my_list)
list(col1)  # => [1, 5, 3]

Similarly, to get the second column:

_, col2, *_ = zip(*my_list)
list(col2)  # => [1, 6, 3]

Transpose a matrix [list(x) for x in zip(*my_list)] The above yields the transposed matrix as a list of rows.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

IteratorsData StructuresListsDictionariescode-tips
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.