0% found this document useful (0 votes)
14 views3 pages

Python List Operations Guide

This document is a cheat sheet for Python list operations, covering basic operations, iteration patterns, list comprehensions, and advanced functions. It includes examples for each operation, such as concatenation, slicing, filtering, and mapping. Additionally, it provides real-life examples demonstrating how to flatten lists, filter and transform data, and check conditions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Python List Operations Guide

This document is a cheat sheet for Python list operations, covering basic operations, iteration patterns, list comprehensions, and advanced functions. It includes examples for each operation, such as concatenation, slicing, filtering, and mapping. Additionally, it provides real-life examples demonstrating how to flatten lists, filter and transform data, and check conditions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python List Operations Cheat Sheet

1️⃣ Basic Operations

Operation / Function What it does Example

len(list) Returns number of elements len([1,2,3]) → 3

Indexing Access an element by position lst[0] → 1

Negative indexing Access from end lst[-1] → last element

Slicing Get a sublist [start:end:step] lst[1:4] → elements 1,2,3

Concatenation (+) Merge two lists into a new one [1,2] + [3,4] → [1,2,3,4]

Repetition (*) Repeat list elements [0]*3 → [0,0,0]

in / not in Membership check 3 in [1,2,3] → True

min(), max() Find smallest / largest max([1,5,3]) → 5

sum() Sum numeric elements sum([1,2,3]) → 6

2️⃣ Iteration Patterns

Pattern What it does Example

for loop Traverse elements for x in lst: print(x)

enumerate() Get index + element for i, x in enumerate(lst): ...

zip() Combine multiple iterables for a,b in zip([1,2],[3,4]): ...

reversed() Iterate in reverse order for x in reversed(lst): ...

sorted() Iterate over sorted copy for x in sorted(lst): ...

3️⃣ List Comprehensions & Expressions

• Basic: [x*2 for x in lst] → [2,4,6]


• With condition: [x for x in lst if x%2==0] → only even numbers
• Nested: [y for x in matrix for y in x] → flatten a 2D list
• With function: [func(x) for x in lst] → apply a function to all elements

4️⃣ Advanced / Deeper Level Operations

1
Operation /
Purpose Example
Function

Check conditions across all / any


all() / any() all(x>0 for x in lst)
elements

map(func, iterable) Apply a function to all items list(map(str, [1,2])) → ['1','2']

Keep elements that satisfy


filter(func, iterable) list(filter(lambda x: x%2==0, lst))
condition

reduce(func,
Reduce list to single value from functools import reduce
iterable)

Combine multiple iterables


[Link]() list(chain([1,2],[3,4]))
efficiently

list(product([1,2],[3,4])) → [(1,3),(1,4),
[Link]() Cartesian product
(2,3),(2,4)]

list slicing with step Select every nth element lst[::2]

copy() / deepcopy() Make independent copies of lists See previous explanation

del lst[i:j] Remove slice of elements del lst[1:3]

⚙️ Real-Life Examples

Flatten nested list:

matrix = [[1,2],[3,4]]
flat = [y for x in matrix for y in x] # [1,2,3,4]

Filter and transform:

numbers = [1,2,3,4,5]
squares_of_even = [x**2 for x in numbers if x%2==0] # [4,16]

Check all conditions:

grades = [90, 85, 78]


all_pass = all(g>=50 for g in grades) # True

Iterate with index and value:

2
names = ["Alice", "Bob"]
for i, name in enumerate(names):
print(i, name)

Merge multiple sources:

a = [1,2]; b=[3,4]
combined = list([Link](a,b)) # [1,2,3,4]

Common questions

Powered by AI

The sum of numeric elements in a list can be calculated using the sum() function. For example, sum([1,2,3]) will return 6 .

Mapping and filtering can be combined to perform transformations where you'd first filter the elements meeting certain conditions and then apply a function to transform these filtered elements. For example, given a list of numbers, you can first filter to get only even numbers via filter(lambda x: x % 2 == 0, numbers), then map them to their squares via map(lambda x: x**2, even_numbers), effectively yielding the squares of all even numbers in the list .

Negative indexing is used to access elements from the end of a list, allowing for reverse traversal. For example, lst[-1] accesses the last element. Slicing, on the other hand, is used to obtain a sublist from the original list using specified start, end, and step indices (lst[start:end:step]). Slicing can also employ negative indices. The main difference is that negative indexing specifies single elements from the back while slicing can extract a continuous segment of the list .

List comprehension with a function simplifies operations by applying the function directly to each element in the list within a single, concise expression. For example, if we have a list lst containing integers and we want to convert them to strings, we can use [str(x) for x in lst]. This is equivalent to using the map() function but allows for inline conditions and more readable syntax .

The itertools.chain() method is used to efficiently combine multiple iterables into a single iterable without creating intermediary lists, which can be memory-intensive. This is especially useful in scenarios involving large datasets or multiple sequences where performance and memory efficiency are critical. Unlike simple list concatenation with the + operator, itertools.chain() avoids creating new list objects for each pair of lists being concatenated .

Using a reversed iterator in Python allows for traversing a list in reverse order without affecting the original list. It offers advantages like improved readability and simplicity when inverse logic or comparison against elements from the end is needed. Typical use cases include parsing sequences backward, undoing operations, or comparison operations like checking for palindromes. The reversed() function efficiently facilitates these operations by providing a reverse iterator over the list, preserving memory as it doesn't create a reversed copy of the list .

enumerate() is used to iterate over a list while maintaining the index of each element, which is helpful when both the element and its position are needed (e.g., printing items with their indexes). In contrast, zip() is used to iterate over multiple lists in parallel, aligning elements by their positions, which is useful when paired data from different lists are needed, like pairing names and scores from two separate lists (e.g., zip(['alice', 'bob'], [85, 90])). enumerate() enhances indexing tasks, while zip() aids in handling synchronous data across multiple lists .

The reduce() function from functools plays a critical role in processing lists by performing a rolling computation to sequential pairs of values in a list, ultimately reducing the list to a single value. It might be preferred over iterative techniques as it provides a declarative approach to implement binary operations like sum, product, or finding the greatest common divisor, potentially improving readability and reducing boilerplate code when concise operations are desired .

The filter() function improves list manipulation by selecting elements that meet a specified condition, enhancing code clarity and conciseness. It offers benefits over loops by allowing the filtering logic to be expressed declaratively, without explicitly handling iteration. This approach can lead to clearer, more maintenance-friendly code. Moreover, filter() can be more efficient as it processes elements lazily, which can be advantageous for large datasets .

The Cartesian product of sets aids in combinatorial problem-solving by generating all possible ordered combinations of elements from multiple sets, which is crucial in fields like operations research, optimization, and probability. The itertools.product() method in Python facilitates this computation, enabling efficient generation of the Cartesian product of two or more iterables, which can help in simulating all possible scenarios or configurations required in complex problem-solving .

You might also like