Python Tutorial– Zip, Reversed and Sorted Function

Python - Zip Function

The zip function is one of Python's built-in functions that can "compress" multiple sequences (lists, tuples, dictionaries, collections, strings, and lists consisting of range intervals) into a single zip object. The so-called "compression" is actually recombining the elements at the corresponding positions in these sequences to generate new tuples.

Unlike Python 3.x, the zip () function in Python 2.x returns a list directly instead of a zip object. However, the returned list or zip object contains the same elements (both tuples).

The syntax of the zip () function is:

zip (iterable, ...)

Where iterable, ... represents multiple lists, tuples, dictionaries, collections, strings, and even range intervals.

The following program demonstrates the basic usage of the zip function:

my_list = [11,12,13]
my_tuple = (21,22,23)
print([x for x in zip(my_list,my_tuple)])
my_dic = {31:2,32:4,33:5}
my_set = {41,42,43,44}
print([x for x in zip(my_dic)])
my_pychar = "python"
my_shechar = "shell"
print([x for x in zip(my_pychar,my_shechar)])

The output is:

[(11, 21), (12, 22), (13, 23)]
[(31,), (32,), (33,)]
[('p', 's'), ('y', 'h'), ('t', 'e'), ('h', 'l'), ('o', 'l')]

If the reader analyzes the above program and the corresponding output results, it is not difficult to find that when using the zip function to "compress" multiple sequences, it will take the first element, the second element, until n elements, each forming a new tuple. It should be noted that when the number of elements in multiple sequences is inconsistent, the shortest sequence will prevail for compression.

In addition, for the zip object returned by the zip function, you can either extract the stored tuples by traversing like the program above, or you can force the zip object into a list by calling the list function like the following program :

my_list = [11,12,13]
my_tuple = (21,22,23)
print (list (zip (my_list, my_tuple)))

The program execution result is:

[(11, 21), (12, 22), (13, 23)]

Python - Reversed Function

Reserved is one of the built-in functions of Python. Its function is for a given sequence (including lists, tuples, strings, and range (n) intervals). This function can return an iterator over the reversed sequence (used to traverse the Reverse sequence).

The syntax of the reserved function is as follows:

reversed (seq)

Among them, seq can be a list, an element, a string, and a list of intervals generated by range.

The following program demonstrates the basic usage of the reversed function:

#Reverse the list
print ([x for x in reversed ([1,2,3,4,5])])
#Reverse the tuples
print ([x for x in reversed ((1,2,3,4,5))])
#Reverse string
print ([x for x in reversed ("abcdefg")])
#Reverse the list of ranges generated by range ()
print ([x for x in reversed (range (10))])

The program execution result is:

[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
['g', 'f', 'e', 'd', 'c', 'b', 'a']
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In addition to using list comprehensions, you can also use the list function to directly convert the iterator returned by the reversed function into a list. Example:

#Reverse list
print (list (reversed ([1,2,3,4,5])))

The output is:

[5, 4, 3, 2, 1]

Again, using the reversed function to reverse the order does not modify the order of the elements in the original sequence, for example:

a = [1,2,3,4,5]
#Reverse the list
print (list (reversed (a)))
print ("a =", a)

The output is:

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

Python - Sorted Function

Sorted is one of Python's built-in functions that sorts sequences (lists, tuples, dictionaries, collections, and even strings).

The basic syntax of the sorted function is as follows:

list = sorted (iterable, key = None, reverse = False)

Among them, iterable indicates the specified sequence, and the key parameter can customize the collation; the reverse parameter specifies whether to sort in ascending (False, default) or descending (True) order. The sorted () function returns a sorted list.

Note that the key and reverse parameters are optional and can be used or ignored.

The following program demonstrates the basic usage of the sorted function:

#Sort the list
a = [5,3,4,2,1]
print (sorted (a))
#Sort tuples
a = (5,4,3,1,2)
print (sorted (a))
#The dictionary is sorted by key by default
a = {4: 1, \
     5: 2, \
     3: 3, \
     2: 6, \
     1: 8}
print (sorted (a.items ()))
#Sort the collection
a = {1,5,3,2,4}
print (sorted (a))
#Sort the strings
a = "51423"
print (sorted (a))

The program execution result is:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[(1, 8), (2, 6), (3, 3), (4, 1), (5, 2)]
[1, 2, 3, 4, 5]
['1', '2', '3', '4', '5']

Again, using the sorted function to sort a sequence does not modify the original sequence, but regenerates a sorted list. Example:

a = [5,3,4,2,1] #Sort the list
print (sorted (a))
#Output the original list again a
print (a)

The output is:

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

Obviously, the sorted function does not change the sequence passed in, but returns a new, sorted list.

In addition, the sorted function sorts the elements in the sequence in ascending order by default. You can achieve descending order by manually changing its reverse parameter value to True. Example:

a = [5,3,4,2,1] #Sort the list
print (sorted (a, reverse = True))

The output is:

[5, 4, 3, 2, 1]

In addition, when calling the sorted function, you can also pass in a key parameter, which can accept a function whose function is to specify the criteria by which the sorted () function is sorted. Example:

chars = ['http: //', \
       'http: //', \
       'http: //', \
       'http: //', \
print (sorted (chars)) #Default sort
#Custom sort by string length
print (sorted (chars, key = lambda x: len (x)))

The output is:

['http: //', 'http: //', 'http: //', 'http: //', 'http://']
['http: //', 'http: //', 'http: //', 'http: //', 'http://']


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises