Advanced Python 4 | List Methods, Tuple Methods, List Comprehensions, Map, Lambda, Filter, and…

Series: Advanced Python

Advanced Python 4 | List Methods, Tuple Methods, List Comprehensions, Map, Lambda, Filter, and Reduce

  1. Methods for Lists and Tuples

The dir() function can give us all the attributes of a given class. For example, if we ignore all the attributes start with a '__’ sign (which means private attributes), then we can get a list of methods (public attributes) for any given class. We can use this to print all the methods of a list.

[method for method in dir(list) if not method.startswith('__')]

Then we can have,

['append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']

We can also do it to the tuple.

[method for method in dir(tuple) if not method.startswith('__')]

Then we can have,

['count', 'index']

We can also use tab after . , then the compiler will give us a list of methods we can choose and use for a given object.

(1) In-place Method

For some of the methods we use, it will replace the original value with the return value without an assigning statement. This is called an in-place method.

(2) Sort Method

The .sort() method will return a sorted list. This method is an in-place method so that we don’t have to assign it back. The list is sorted in the following sequence:

  • For numbers: sort from negative numbers to positive numbers
  • For characters: sort from number chars, then from A to z
  • For string: Follow the same sorting query of the characters
  • We can not mix data types for sorting (characters and strings can be mixed for sorting), and also, we can not sort for data types expect for numbers, characters, and string.

Note that if we want to reverse the result, we can set the reverse parameter to True .

  • Example: What is the output of the following program?

Output:

None

This is because the sort method is an in-place method so it returns None as it’s value.

(3) Append and Extend Method

The .append() method will put a new element in the last of the list, while the .extend() method will extend the list with a given sequence. This method is an in-place method so that we don’t have to assign it back.

  • Example #1. What is the output of the following program?
print(['a', 'AB', 'CB', 'b'].sort(reverse=True))
view raw list_1.py hosted with ❤ by GitHub

Output:

Error

This is because + operator can only concentrate list to list.

  • Example #2. What is the output of the following program?
a = [42]
t = (42, 42)
a = a + t
print(a)
view raw list_2.py hosted with ❤ by GitHub

Output:

[42, 42, 42]

This is because += operator can be used to concentrate tuple to list.

  • Example #3. What is the output of the following program?
a = [42]
t = (42, 42)
a += t
a
view raw list_3.py hosted with ❤ by GitHub

Output:

Error

This is because we can’t append nothing to a list, append must have a parameter.

  • Example #4. What is the output of the following program?
A = [42, 42]
A.append()
print(A)
view raw list_4.py hosted with ❤ by GitHub

Output:

[42, 42, None]

This is because None is not nothing, it is actually a type of data.

  • Example #5. What is the output of the following program?
A = [42, 42]
B = 42
A.extend(B)
print(A)
view raw list_6.py hosted with ❤ by GitHub

Output:

Error

This is because we can’t expend the list with a single value.

  • Example #6. What is the output of the following program?
A = [42, 42]
B = '42'
A.extend(B)
print(A)
view raw list_7.py hosted with ❤ by GitHub

Output:

[42, 42, '4', '2']

This can be hard to answer because people forget the string is actually a list of chars in this case. If we want to add ‘42’ directly in the end, we have to use append to treat that as a whole, which is,

A = [42, 42]
B = '42'
A.append(B)
print(A)
  • Example #7. What is the output of the following program?
A = [42, 42]
B = (42)
A.extend(B)
print(A)
view raw list_8.py hosted with ❤ by GitHub

Output:

Error

Even if we use the parentheses for B, this still means an integer instead of a tuple. So it can not be extended to a given list.

  • Example #8. What is the output of the following program?
A = [42, 42]
B = [(42)]
A.extend(B)
print(A)
view raw list_9.py hosted with ❤ by GitHub

Output:

[42, 42, 42]

This program is equivalent to,

A = [42, 42]
B = [42]
A.extend(B)
print(A)
  • Example #9. What is the output of the following program?
A = [42, 42]
B = {42}
A.extend(B)
print(A)
view raw list_10.py hosted with ❤ by GitHub

Output:

[42, 42, 42]

The list can be extended by a set. Note that the element of a set can not be a list (tuple is okay).

  • Example #10. What is the output of the following program?
A = [42, 42]
A.extend(A)
print(A)
view raw list_14.py hosted with ❤ by GitHub

Output:

[42, 42, 42, 42]

(4) List Slicing

Note that we can use [::-1] to reverse a list.

  • Example #1. What is the output of the following program?
letters = ["a", "b", "c", "d", "e"]
print(letters[-1:-5])
view raw list_11.py hosted with ❤ by GitHub

Output:

[]

By default, the step of slicing will be set to positive 1.

  • Example #2. What is the output of the following program?
nums = [1, 2, 3, 4, 5, 6]
print(nums[20:2:-1])
view raw list_12.py hosted with ❤ by GitHub

Output:

[6, 5, 4]

We can slice out of the range of the list.

  • Example #3. What is the output of the following program?
nums = [1, 2, 3, 4, 5, 6]
print(nums[20])
view raw list_13.py hosted with ❤ by GitHub

Output:

Error

(5) List Copy

Because the list is mutable, so we can not assign a list to another with an assigning statement. We have to use .copy() method for assigning.

  • Example #1. What is the output of the following program?
nums = [1, 42]
nums_copy = nums
nums_copy[0] = 42
print(nums)

Output:

[42, 42]
  • Example #2. What is the output of the following program?
nums = [1, 42]
nums_copy = nums.copy()
nums_copy[0] = 42
print(nums)
view raw use_copy.py hosted with ❤ by GitHub

Output:

[1, 42]

(6) List Element Types

The element in a list must be an object. For example, all functions can be elements in the list while some of the reserved keywords can not be put into the list.

  • Example #1. What is the output of the following program?
nums = [1, 2, 3]
if [42, "ABC", "🐶", True, nums, sum, nums.sort, hash, range(2), None, Ellipsis, int]:
print(True)

Output:

True
  • Example #2. What is the output of the following program?
if [if, for, not, in, with, return, not_defined_variable, lambda]:
print(True)

Output:

Error

(7) Other List Methods

  • Example #1. What is the output of the following program?
nums = [1, 2, 3, 4]
nums.clear
print(nums)
view raw list_15.py hosted with ❤ by GitHub

Output:

[1, 2, 3, 4]

We just write the function in the second line, but we didn’t apply it to the list. Therefore, the result won’t change. If we want to clear the list, we have to type the parenthesis.

nums = [1, 2, 3, 4]
nums.clear()
nums

Note that the clear method takes no arguments, or it will return us an error.

  • Example #2. What is the output of the following program?
nums = [1, 3, 4, 1, 2, 2, 2, 3, 4]
print([nums.count(i) for i in set(nums)])
view raw list_16.py hosted with ❤ by GitHub

Output:

[2, 3, 2, 2]

This will count the occurring times of all elements in the list.

  • Example #3. What is the output of the following program?
nums = [1, 2, 4, 1, 5, 2, 2, 3, 4]
print(nums.index(2, 3, 6))
view raw list_17.py hosted with ❤ by GitHub

Output:

5

This is the same as,

print(nums[3:6].index(2) + len(nums[0:3]))
  • Example #4. What is the output of the following program?
nums = [1, 2, 4, 1, 5, 2, 2, 3, 4]
nums.insert(-100, 'i')
print(nums)
view raw list_18.py hosted with ❤ by GitHub

Output:

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

The index we provide for the insert method can be negative, and it can also be out of the range of the list.

  • Example #5. What is the output of the following program?
mylist = [1,2,4]
print(mylist.pop(1))
print(mylist)
view raw list_19.py hosted with ❤ by GitHub

Output:

2 
[1, 4]

We can pop any element by its index. This index can be negative but can not be out of range.

  • Example #6. What is the output of the following program?
elist = []
print(elist.pop())
view raw list_20.py hosted with ❤ by GitHub

Output:

Error

Can not pop from an empty set.

  • Example #7. What is the output of the following program?
nums = [1, 2, 4, 1, 5, 2, 2, 3, 4]
print(nums.remove(3))
print(nums)
view raw list_21.py hosted with ❤ by GitHub

Output:

None 
[1, 2, 4, 1, 5, 2, 2, 4]

Note that remove is to remove the first value of the argument in the list, while pop is to pop the value locates in the argument index. It is also important to know that the remove method returns no value.

(8) Tuple Methods

There are only two methods for a tuple: .count() and .index(). The tuples can also do slicing.

  • Example #1. What is the output of the following program?
nums = (1, 2, 4, 1, 5, 2, 2, 3, 4)
[nums.count(i) for i in set(nums)]
view raw tuple_1.py hosted with ❤ by GitHub

Output:

[2, 3, 1, 2, 1]

This is quite similar to a list.

  • Example #2. What is the output of the following program?
A = (42, 42)
B = A
B[0] = 1
print(A)
view raw tuple_assign.py hosted with ❤ by GitHub

Output:

Error

We can not assign by the index of a tuple. If we must change the value of a tuple, we can use the following code,

A = (42, 42)
B = list(A)
B[0] = 1
print(A)
print(tuple(B))

this will give us,

(42, 42) 
(1, 42)
  • Example #3. What is the output of the following program?
nums = (1, 2, 4, 1, 5, 2, 2, 3, 4)
print(nums.index(2))
view raw tuple_2.py hosted with ❤ by GitHub

Output:

1

2. List Comprehension

(1) List Comprehension

The list comprehension is a cool way to generate a list. It has the form of,

(return) [<fun> for <item> in <sequence> (if <condition>)]

The function in this could be any function, including the in-built functions, the functions from packages, or the functions defined by us.

  • Example #1. What is the output of the following program?
my_string = "Hello World!"
print([print(i) for i in my_string if i not in "aeiou"])
view raw list_comp_1.py hosted with ❤ by GitHub

Output:

H 
l
l

W
r
l
d
!
[None, None, None, None, None, None, None, None, None]
  • Example #2. What is the output of the following program?
x = [i**+2 for i in range(3)]
print(x)
view raw list_comp_2.py hosted with ❤ by GitHub

Output:

[0, 1, 4]

This is the same as,

x = [i**2 for i in range(3)]
print(x)

(2) The map Object

The general form of a map object can be calculate through the map function. The general form of the map function is,

map(func, *iterables)

The func function can be any function, including the in-built functions, the functions from packages, or the functions defined by us. The map object is to take each of the iterables as the an argument of this function.

  • Example. What is the output of the following program?
print(list(map(print, range(5))))
view raw map_func.py hosted with ❤ by GitHub

Output:

0 
1
2
3
4
[None, None, None, None, None]

(3) lambda Functions

lambda functions in Python are anonymous functions. lambda functions are also called in-line or throw-away functions. For example, if we write,

lambda n: n*n

It is equivalent to write (can not run the following code, because we will have namespace problem),

def fun(n):
def square(n):
return n * n
return square

So that if we have,

tuple(map(lambda n: n*n, range(11)))

this is equivalent to,

def square(n):
return n * n
tuple(map(square, range(11)))
  • Example. What is the output of the following program?
print(list(map(lambda x, y: x+y, [1,2,3,4,5], [6,7,8,9,0])))

Output:

[7, 9, 11, 13, 5]

(4) filter Function

The filter has a similar constructure of the map function, which is,

filter(function or None, iterable)

It is different from the map because it doesn’t contain any return value from the function. In fact, the filter uses the return value of the function as a boolean value and use this value to judge whether or not putting the iterables into the filter. If the return value from the function is false, then we just ignore its argument and the filter will not contain the particular argument value of this function.

  • Example. What is the output of the following program?
print(list(filter(print, range(5))))
view raw filter_func.py hosted with ❤ by GitHub

Output:

0 
1
2
3
4
[]

(5) reduce Function

The reduce is not a in-built function, so we have to import it before we use it.

from functools import reduce

For everytime of the calculation, the lambda (or the other given function) will take in two values, and it is going to return one value. In the next iteration, it will treat this result as the first argument and then put in another new iterable as the second argument.

  • Example #1. What is the output of the following program?
from functools import reduce
print(reduce(lambda total, n: total+n, [1, 2, 3, 4, 5]))
view raw reduce_2.py hosted with ❤ by GitHub

Output:

15
  • Example #2. What is the output of the following program?
from functools import reduce
words = ["mary", "had", "a", "little", "lamb"]
biggest_word = reduce(lambda x, y: x if len(x) > len(y) else y, words)
print(biggest_word)
view raw reduce_1.py hosted with ❤ by GitHub

Output:

little

3. General Questions

  • Example #1. What is the output of the following program?
func = lambda x: return x
print(func(2))
view raw gq_1.py hosted with ❤ by GitHub

Output:

Error

In a lambda function, statements like return, pass, assert, or raise will raise a SyntaxError exception.

  • Example #2. What is the output of the following program?
nums = ([1, 2, 3], [4, 5, 6])
nums[0][2] = 0
result = nums
print(result)
view raw gq_7.py hosted with ❤ by GitHub

Output:

([1, 2, 0], [4, 5, 6])

We can change the mutable element in an immutable one.