or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arrays.mdchaining.mdcollections.mdfunctions.mdindex.mdnumerical.mdobjects.mdpredicates.mdstrings.mdutilities.md

collections.mddocs/

0

# Collections Module

1

2

The Collections module provides 33 functions that operate on both arrays and objects (dictionaries). These functions are designed to work with any iterable collection and include operations for filtering, mapping, grouping, and reducing data.

3

4

## Core Collection Functions

5

6

### at

7

8

```python { .api }

9

def at(collection: Union[Mapping, Iterable], *paths) -> List[Any]

10

```

11

12

Creates a list of elements corresponding to the given keys or indexes. For arrays, provide indexes; for objects, provide property paths.

13

14

**Parameters:**

15

- `collection` (`Union[Mapping, Iterable]`): Collection to iterate over.

16

- `paths` (`*Union[str, int]`): Property paths to pick or indexes to select.

17

18

**Returns:**

19

- `List[Any]`: New list of picked elements.

20

21

**Example:**

22

```python { .api }

23

from pydash import at

24

25

# Array indexing

26

at(['a', 'b', 'c'], 0, 2)

27

# ['a', 'c']

28

29

# Object property access

30

at({'a': 1, 'b': 2, 'c': 3}, 'a', 'c')

31

# [1, 3]

32

```

33

34

### every

35

36

```python { .api }

37

def every(collection: Iterable, predicate=None) -> bool

38

```

39

40

Checks if predicate returns truthy for all elements of collection. Iteration is stopped once predicate returns falsey.

41

42

**Parameters:**

43

- `collection` (`Iterable`): Collection to iterate over.

44

- `predicate` (`Callable`, optional): Function invoked per iteration.

45

46

**Returns:**

47

- `bool`: `True` if all elements pass the predicate check, else `False`.

48

49

**Example:**

50

```python { .api }

51

from pydash import every

52

53

every([2, 4, 6], lambda x: x % 2 == 0)

54

# True

55

56

every([2, 3, 6], lambda x: x % 2 == 0)

57

# False

58

59

# Using property shorthand

60

every([{'active': True}, {'active': True}], 'active')

61

# True

62

```

63

64

### filter_

65

66

```python { .api }

67

def filter_(collection: Iterable, predicate=None) -> List[Any]

68

```

69

70

Iterates over elements of collection, returning a list of all elements predicate returns truthy for.

71

72

**Parameters:**

73

- `collection` (`Iterable`): Collection to iterate over.

74

- `predicate` (`Callable`, optional): Function invoked per iteration.

75

76

**Returns:**

77

- `List[Any]`: New filtered list.

78

79

**Example:**

80

```python { .api }

81

from pydash import filter_

82

83

filter_([1, 2, 3, 4], lambda x: x % 2 == 0)

84

# [2, 4]

85

86

# Using dict predicate

87

users = [{'name': 'John', 'active': True}, {'name': 'Jane', 'active': False}]

88

filter_(users, {'active': True})

89

# [{'name': 'John', 'active': True}]

90

```

91

92

### find

93

94

```python { .api }

95

def find(collection: Iterable, predicate=None, from_index: int = 0) -> Any

96

```

97

98

Iterates over elements of collection, returning the first element predicate returns truthy for.

99

100

**Parameters:**

101

- `collection` (`Iterable`): Collection to inspect.

102

- `predicate` (`Callable`, optional): Function invoked per iteration.

103

- `from_index` (`int`): Index to search from. Defaults to `0`.

104

105

**Returns:**

106

- `Any`: Matched element, else `None`.

107

108

**Example:**

109

```python { .api }

110

from pydash import find

111

112

find([1, 2, 3, 4], lambda x: x > 2)

113

# 3

114

115

users = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]

116

find(users, lambda u: u['age'] < 30)

117

# {'name': 'Jane', 'age': 25}

118

```

119

120

### find_last

121

122

```python { .api }

123

def find_last(collection: Iterable, predicate=None, from_index: int = -1) -> Any

124

```

125

126

Like `find` except that it iterates over elements from right to left.

127

128

**Parameters:**

129

- `collection` (`Iterable`): Collection to inspect.

130

- `predicate` (`Callable`, optional): Function invoked per iteration.

131

- `from_index` (`int`): Index to search from. Defaults to `-1`.

132

133

**Returns:**

134

- `Any`: Matched element, else `None`.

135

136

**Example:**

137

```python { .api }

138

from pydash import find_last

139

140

find_last([1, 2, 3, 4], lambda x: x > 2)

141

# 4

142

```

143

144

### includes

145

146

```python { .api }

147

def includes(collection: Iterable, target: Any, from_index: int = 0) -> bool

148

```

149

150

Checks if target is in collection using SameValueZero for equality comparisons.

151

152

**Parameters:**

153

- `collection` (`Iterable`): Collection to inspect.

154

- `target` (`Any`): Value to search for.

155

- `from_index` (`int`): Index to search from. Defaults to `0`.

156

157

**Returns:**

158

- `bool`: `True` if target is found, else `False`.

159

160

**Example:**

161

```python { .api }

162

from pydash import includes

163

164

includes([1, 2, 3], 1)

165

# True

166

167

includes([1, 2, 3], 1, 2)

168

# False

169

170

includes({'a': 1, 'b': 2}, 1)

171

# True

172

```

173

174

### map_

175

176

```python { .api }

177

def map_(collection: Iterable, iteratee=None) -> List[Any]

178

```

179

180

Creates a list of values by running each element in collection through iteratee.

181

182

**Parameters:**

183

- `collection` (`Iterable`): Collection to iterate over.

184

- `iteratee` (`Callable`, optional): Function invoked per iteration.

185

186

**Returns:**

187

- `List[Any]`: New mapped list.

188

189

**Example:**

190

```python { .api }

191

from pydash import map_

192

193

map_([1, 2, 3], lambda x: x ** 2)

194

# [1, 4, 9]

195

196

# Using property shorthand

197

users = [{'name': 'John'}, {'name': 'Jane'}]

198

map_(users, 'name')

199

# ['John', 'Jane']

200

```

201

202

### size

203

204

```python { .api }

205

def size(collection: Sized) -> int

206

```

207

208

Gets the size of collection by returning its length for array-like values or the number of enumerable string keyed properties for objects.

209

210

**Parameters:**

211

- `collection` (`Sized`): Collection to inspect.

212

213

**Returns:**

214

- `int`: Collection size.

215

216

**Example:**

217

```python { .api }

218

from pydash import size

219

220

size([1, 2, 3])

221

# 3

222

223

size({'a': 1, 'b': 2})

224

# 2

225

226

size('hello')

227

# 5

228

```

229

230

### some

231

232

```python { .api }

233

def some(collection: Iterable, predicate=None, from_index: int = 0) -> bool

234

```

235

236

Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy.

237

238

**Parameters:**

239

- `collection` (`Iterable`): Collection to iterate over.

240

- `predicate` (`Callable`, optional): Function invoked per iteration.

241

- `from_index` (`int`): Index to search from. Defaults to `0`.

242

243

**Returns:**

244

- `bool`: `True` if any element passes the predicate check, else `False`.

245

246

**Example:**

247

```python { .api }

248

from pydash import some

249

250

some([1, 2, 3, 4], lambda x: x > 3)

251

# True

252

253

some([1, 2, 3, 4], lambda x: x > 5)

254

# False

255

```

256

257

## Collection Grouping and Organization

258

259

### count_by

260

261

```python { .api }

262

def count_by(collection: Iterable, iteratee=None) -> Dict[Any, int]

263

```

264

265

Creates a dictionary composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.

266

267

**Parameters:**

268

- `collection` (`Iterable`): Collection to iterate over.

269

- `iteratee` (`Callable`, optional): Function invoked per iteration.

270

271

**Returns:**

272

- `Dict[Any, int]`: New dictionary with counts.

273

274

**Example:**

275

```python { .api }

276

from pydash import count_by

277

278

count_by(['one', 'two', 'three'], len)

279

# {3: 2, 5: 1}

280

281

count_by([6.1, 4.2, 6.3], lambda x: int(x))

282

# {6: 2, 4: 1}

283

```

284

285

### group_by

286

287

```python { .api }

288

def group_by(collection: Iterable[T], iteratee=None) -> Dict[Any, List[T]]

289

```

290

291

Creates a dictionary composed of keys generated from the results of running each element of collection through iteratee. The order of grouped values is determined by the order they occur in collection.

292

293

**Parameters:**

294

- `collection` (`Iterable[T]`): Collection to iterate over.

295

- `iteratee` (`Callable`, optional): Function invoked per iteration.

296

297

**Returns:**

298

- `Dict[Any, List[T]]`: New dictionary with grouped elements.

299

300

**Example:**

301

```python { .api }

302

from pydash import group_by

303

304

group_by(['one', 'two', 'three'], len)

305

# {3: ['one', 'two'], 5: ['three']}

306

307

group_by([6.1, 4.2, 6.3], lambda x: int(x))

308

# {6: [6.1, 6.3], 4: [4.2]}

309

```

310

311

### key_by

312

313

```python { .api }

314

def key_by(collection: Iterable[T], iteratee=None) -> Dict[Any, T]

315

```

316

317

Creates a dictionary composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the last element responsible for generating the key.

318

319

**Parameters:**

320

- `collection` (`Iterable[T]`): Collection to iterate over.

321

- `iteratee` (`Callable`, optional): Function invoked per iteration.

322

323

**Returns:**

324

- `Dict[Any, T]`: New dictionary with keyed elements.

325

326

**Example:**

327

```python { .api }

328

from pydash import key_by

329

330

users = [{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Jane'}]

331

key_by(users, 'id')

332

# {1: {'id': 1, 'name': 'John'}, 2: {'id': 2, 'name': 'Jane'}}

333

```

334

335

### nest

336

337

```python { .api }

338

def nest(collection: Iterable[Any], *properties: Any) -> Any

339

```

340

341

Returns a nested dictionary where each key is an array of values from the corresponding properties.

342

343

**Parameters:**

344

- `collection` (`Iterable[Any]`): Collection to nest.

345

- `properties` (`*Any`): Properties to group by.

346

347

**Returns:**

348

- `Any`: Nested dictionary structure.

349

350

**Example:**

351

```python { .api }

352

from pydash import nest

353

354

data = [

355

{'shape': 'square', 'color': 'red', 'used': 1, 'instances': 1},

356

{'shape': 'circle', 'color': 'red', 'used': 2, 'instances': 1}

357

]

358

nest(data, 'color', 'shape')

359

```

360

361

### order_by

362

363

```python { .api }

364

def order_by(collection: Iterable, iteratees=None, orders=None, reverse=False) -> List[Any]

365

```

366

367

Creates a list of elements sorted in ascending order by the results of running each element in a collection through each iteratee.

368

369

**Parameters:**

370

- `collection` (`Iterable`): Collection to iterate over.

371

- `iteratees` (`List[Callable]`, optional): Iteratees to sort by.

372

- `orders` (`List[str]`, optional): Sort orders of iteratees ('asc' or 'desc').

373

- `reverse` (`bool`): Whether to reverse the sort order. Defaults to `False`.

374

375

**Returns:**

376

- `List[Any]`: New sorted list.

377

378

**Example:**

379

```python { .api }

380

from pydash import order_by

381

382

users = [

383

{'name': 'John', 'age': 30},

384

{'name': 'Jane', 'age': 25},

385

{'name': 'Bob', 'age': 30}

386

]

387

order_by(users, ['age', 'name'], ['asc', 'desc'])

388

# [{'name': 'Jane', 'age': 25}, {'name': 'John', 'age': 30}, {'name': 'Bob', 'age': 30}]

389

```

390

391

### partition

392

393

```python { .api }

394

def partition(collection: Iterable, predicate=None) -> List[List[Any]]

395

```

396

397

Creates a list of two lists, the first of which contains elements predicate returns truthy for, the second of which contains elements predicate returns falsey for.

398

399

**Parameters:**

400

- `collection` (`Iterable`): Collection to iterate over.

401

- `predicate` (`Callable`, optional): Function invoked per iteration.

402

403

**Returns:**

404

- `List[List[Any]]`: New list with partitioned elements.

405

406

**Example:**

407

```python { .api }

408

from pydash import partition

409

410

partition([1, 2, 3, 4], lambda x: x % 2 == 0)

411

# [[2, 4], [1, 3]]

412

```

413

414

### sort_by

415

416

```python { .api }

417

def sort_by(collection: Iterable, iteratee=None, reverse=False) -> List[Any]

418

```

419

420

Creates a list of elements, sorted in ascending order by the results of running each element in a collection through each iteratee.

421

422

**Parameters:**

423

- `collection` (`Iterable`): Collection to iterate over.

424

- `iteratee` (`Callable`, optional): Function invoked per iteration.

425

- `reverse` (`bool`): Whether to reverse the sort order. Defaults to `False`.

426

427

**Returns:**

428

- `List[Any]`: New sorted list.

429

430

**Example:**

431

```python { .api }

432

from pydash import sort_by

433

434

users = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]

435

sort_by(users, 'age')

436

# [{'name': 'Jane', 'age': 25}, {'name': 'John', 'age': 30}]

437

438

sort_by(['banana', 'apple', 'cherry'], len)

439

# ['apple', 'banana', 'cherry']

440

```

441

442

## Collection Processing Functions

443

444

### flat_map

445

446

```python { .api }

447

def flat_map(collection: Iterable, iteratee=None) -> List[Any]

448

```

449

450

Creates a flattened list of values by running each element in collection through iteratee and flattening the mapped results.

451

452

**Parameters:**

453

- `collection` (`Iterable`): Collection to iterate over.

454

- `iteratee` (`Callable`, optional): Function invoked per iteration.

455

456

**Returns:**

457

- `List[Any]`: New flattened list.

458

459

**Example:**

460

```python { .api }

461

from pydash import flat_map

462

463

flat_map([1, 2], lambda x: [x, x])

464

# [1, 1, 2, 2]

465

466

flat_map([{'a': [1, 2]}, {'a': [3, 4]}], 'a')

467

# [1, 2, 3, 4]

468

```

469

470

### flat_map_deep

471

472

```python { .api }

473

def flat_map_deep(collection: Iterable, iteratee=None) -> List[Any]

474

```

475

476

Like `flat_map` except that it recursively flattens the mapped results.

477

478

**Parameters:**

479

- `collection` (`Iterable`): Collection to iterate over.

480

- `iteratee` (`Callable`, optional): Function invoked per iteration.

481

482

**Returns:**

483

- `List[Any]`: New flattened list.

484

485

**Example:**

486

```python { .api }

487

from pydash import flat_map_deep

488

489

flat_map_deep([1, 2], lambda x: [[[x, x]]])

490

# [1, 1, 2, 2]

491

```

492

493

### flat_map_depth

494

495

```python { .api }

496

def flat_map_depth(collection: Iterable, iteratee=None, depth: int = 1) -> List[Any]

497

```

498

499

Like `flat_map` except that it recursively flattens the mapped results up to depth times.

500

501

**Parameters:**

502

- `collection` (`Iterable`): Collection to iterate over.

503

- `iteratee` (`Callable`, optional): Function invoked per iteration.

504

- `depth` (`int`): Maximum recursion depth. Defaults to `1`.

505

506

**Returns:**

507

- `List[Any]`: New flattened list.

508

509

### for_each

510

511

```python { .api }

512

def for_each(collection: Iterable, iteratee=None) -> Any

513

```

514

515

Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).

516

517

**Parameters:**

518

- `collection` (`Iterable`): Collection to iterate over.

519

- `iteratee` (`Callable`, optional): Function invoked per iteration.

520

521

**Returns:**

522

- `Any`: `collection`.

523

524

**Example:**

525

```python { .api }

526

from pydash import for_each

527

528

result = []

529

for_each([1, 2, 3], lambda x: result.append(x * 2))

530

# result is now [2, 4, 6]

531

```

532

533

### for_each_right

534

535

```python { .api }

536

def for_each_right(collection: Iterable, iteratee: Callable) -> Any

537

```

538

539

Like `for_each` except that it iterates over elements from right to left.

540

541

**Parameters:**

542

- `collection` (`Iterable`): Collection to iterate over.

543

- `iteratee` (`Callable`): Function invoked per iteration.

544

545

**Returns:**

546

- `Any`: `collection`.

547

548

### invoke_map

549

550

```python { .api }

551

def invoke_map(collection: Iterable, method_name: str, *args, **kwargs) -> List[Any]

552

```

553

554

Invokes the method at `method_name` of each element in the collection, returning a list of the results of each invoked method.

555

556

**Parameters:**

557

- `collection` (`Iterable`): Collection to iterate over.

558

- `method_name` (`str`): Name of method to invoke.

559

- `args` (`*Any`): Arguments to invoke the method with.

560

- `kwargs` (`**Any`): Keyword arguments to invoke the method with.

561

562

**Returns:**

563

- `List[Any]`: List of results.

564

565

**Example:**

566

```python { .api }

567

from pydash import invoke_map

568

569

invoke_map([[5, 1, 7], [3, 2, 1]], 'sort')

570

# [[1, 5, 7], [1, 2, 3]]

571

```

572

573

### pluck

574

575

```python { .api }

576

def pluck(collection: Iterable[Any], path: str) -> List[Any]

577

```

578

579

Retrieves the value of a specified property from all elements in the collection.

580

581

**Parameters:**

582

- `collection` (`Iterable[Any]`): Collection to pluck.

583

- `path` (`str`): Property path to pluck.

584

585

**Returns:**

586

- `List[Any]`: New list of plucked values.

587

588

**Example:**

589

```python { .api }

590

from pydash import pluck

591

592

users = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]

593

pluck(users, 'name')

594

# ['John', 'Jane']

595

```

596

597

## Collection Reduction Functions

598

599

### reduce_

600

601

```python { .api }

602

def reduce_(collection: Iterable, iteratee=None, accumulator=None) -> Any

603

```

604

605

Reduces collection to a value which is the accumulated result of running each element in collection through iteratee, where each successive invocation is supplied the return value of the previous.

606

607

**Parameters:**

608

- `collection` (`Iterable`): Collection to iterate over.

609

- `iteratee` (`Callable`, optional): Function invoked per iteration.

610

- `accumulator` (`Any`, optional): Initial value.

611

612

**Returns:**

613

- `Any`: Accumulated value.

614

615

**Example:**

616

```python { .api }

617

from pydash import reduce_

618

619

reduce_([1, 2, 3, 4], lambda acc, x: acc + x)

620

# 10

621

622

reduce_([1, 2, 3, 4], lambda acc, x: acc + x, 0)

623

# 10

624

625

# Reduce objects

626

reduce_({'a': 1, 'b': 2, 'c': 1}, lambda acc, val, key: acc + val, 0)

627

# 4

628

```

629

630

### reduce_right

631

632

```python { .api }

633

def reduce_right(collection: Iterable, iteratee=None, accumulator=None) -> Any

634

```

635

636

Like `reduce_` except that it iterates over elements from right to left.

637

638

**Parameters:**

639

- `collection` (`Iterable`): Collection to iterate over.

640

- `iteratee` (`Callable`, optional): Function invoked per iteration.

641

- `accumulator` (`Any`, optional): Initial value.

642

643

**Returns:**

644

- `Any`: Accumulated value.

645

646

**Example:**

647

```python { .api }

648

from pydash import reduce_right

649

650

reduce_right([[0, 1], [2, 3], [4, 5]], lambda acc, x: acc + x, [])

651

# [4, 5, 2, 3, 0, 1]

652

```

653

654

### reductions

655

656

```python { .api }

657

def reductions(collection: Iterable, iteratee=None, accumulator=None, from_right=False) -> List[Any]

658

```

659

660

Like `reduce_` except that it returns a list of each intermediate value in the reduction operation.

661

662

**Parameters:**

663

- `collection` (`Iterable`): Collection to iterate over.

664

- `iteratee` (`Callable`, optional): Function invoked per iteration.

665

- `accumulator` (`Any`, optional): Initial value.

666

- `from_right` (`bool`): Whether to iterate from right to left. Defaults to `False`.

667

668

**Returns:**

669

- `List[Any]`: List of intermediate values.

670

671

**Example:**

672

```python { .api }

673

from pydash import reductions

674

675

reductions([1, 2, 3, 4], lambda acc, x: acc + x)

676

# [1, 3, 6, 10]

677

678

reductions([1, 2, 3, 4], lambda acc, x: acc + x, 0)

679

# [0, 1, 3, 6, 10]

680

```

681

682

### reductions_right

683

684

```python { .api }

685

def reductions_right(collection: Iterable, iteratee=None, accumulator=None) -> List[Any]

686

```

687

688

Like `reductions` except that it iterates over elements from right to left.

689

690

**Parameters:**

691

- `collection` (`Iterable`): Collection to iterate over.

692

- `iteratee` (`Callable`, optional): Function invoked per iteration.

693

- `accumulator` (`Any`, optional): Initial value.

694

695

**Returns:**

696

- `List[Any]`: List of intermediate values.

697

698

### reject

699

700

```python { .api }

701

def reject(collection: Iterable, predicate=None) -> List[Any]

702

```

703

704

The opposite of `filter_`. This method returns the elements of collection that predicate does not return truthy for.

705

706

**Parameters:**

707

- `collection` (`Iterable`): Collection to iterate over.

708

- `predicate` (`Callable`, optional): Function invoked per iteration.

709

710

**Returns:**

711

- `List[Any]`: New filtered list.

712

713

**Example:**

714

```python { .api }

715

from pydash import reject

716

717

reject([1, 2, 3, 4], lambda x: x % 2 == 0)

718

# [1, 3]

719

720

# Using dict predicate

721

users = [{'name': 'John', 'active': True}, {'name': 'Jane', 'active': False}]

722

reject(users, {'active': True})

723

# [{'name': 'Jane', 'active': False}]

724

```

725

726

## Collection Sampling Functions

727

728

### sample

729

730

```python { .api }

731

def sample(collection: Sequence[T]) -> T

732

```

733

734

Gets a random element from collection.

735

736

**Parameters:**

737

- `collection` (`Sequence[T]`): Collection to sample.

738

739

**Returns:**

740

- `T`: Random element.

741

742

**Example:**

743

```python { .api }

744

from pydash import sample

745

746

sample([1, 2, 3, 4])

747

# Random element from the array

748

```

749

750

### sample_size

751

752

```python { .api }

753

def sample_size(collection: Sequence[T], n: int = None) -> List[T]

754

```

755

756

Gets n random elements at unique keys from collection up to the size of collection.

757

758

**Parameters:**

759

- `collection` (`Sequence[T]`): Collection to sample.

760

- `n` (`int`, optional): Number of elements to sample.

761

762

**Returns:**

763

- `List[T]`: Random elements.

764

765

**Example:**

766

```python { .api }

767

from pydash import sample_size

768

769

sample_size([1, 2, 3, 4], 2)

770

# Random 2 elements from the array

771

```

772

773

### shuffle

774

775

```python { .api }

776

def shuffle(collection: Iterable[T]) -> List[T]

777

```

778

779

Creates a list of shuffled values, using a version of the Fisher-Yates shuffle.

780

781

**Parameters:**

782

- `collection` (`Iterable[T]`): Collection to shuffle.

783

784

**Returns:**

785

- `List[T]`: New shuffled list.

786

787

**Example:**

788

```python { .api }

789

from pydash import shuffle

790

791

shuffle([1, 2, 3, 4])

792

# Randomly shuffled version of the array

793

```

794

795

This Collections module provides comprehensive functionality for working with any iterable data structure, whether it's a list, dictionary, or custom iterable. The 31 functions cover all major collection processing patterns including filtering, mapping, reducing, grouping, and sampling operations.