As you start programming in Python you will undoubtedly have to use a collection object. In case you don’t remember, collections class in Python provides access to various objects like (dictionaries, tupples etc). Besides the collections class, Python also supports lists, sets as built-ins. All of these provide you easier ways to store and manipulate data.

In this article, we’ll take a closer look at how you can get some imperatively tedious operations on collections (lists, dictionaries and sets) done in one line with Python built-Ins.

1. Return a section of the collection

1
collection_name[start_index:end_index]

2. Counting the number of elements in a collection

1
2
3
enumerate(collection_name, start=initial number to start the numbering)

enumerate(collection_name[start:end], start=initial number to start the numbering)

3. Applying a function to each element in a collection

1
map (function, collection_name)

4. Finding the maximum/minimum of elements in a collection

(a) Minimum

1
2
min (collection_name)
min(collection_name[start:end])

(b) Maximum

1
2
max(collection_name)
max(collection_name[start:end])

5. Reverse the order of elements in a collection

1
2
reversed(collection_name)
reversed(collection_name[start:end])

6. Sorting elements in a collection

(a) Ascending Order

1
2
sorted(collection_name)
sorted(collection_name[start:end])

(b) Descending Order

1
2
sorted(collection_name,reverse=True)
sorted(collection_name[start:end],reverse=True)

7. Find the sum of elements of a collection

1
2
sum ( collection_name)
sum( collection_name[start:end])

8. Convert a collection to a string

1
2
str(collection_name)
str(collection_name[start:end])

9. Convert a collection to a tuple/list/set

1
2
3
4
5
6
7
8
tuple(collection_name)
tuple(collection_name[start:end])

list(collection_name)
list(collection_name[start:end])

set(collection_name)
set(collection_name[start:end])

10. Display the type of collection

1
type(collection_name)

Leave a Reply

Your email address will not be published. Required fields are marked *