Program to find the elements of Kth column using Python

by | Mar 24, 2021 | Python Programs

Home » Python » Python Programs » Program to find the elements of Kth column using Python

Introduction

In this section, we will discuss the problem to find the element of the kth column in multi-dimensional array through python programming.

Program to find the elements of Kth column

Program

input_list = [[6,4,7], [10,2,5], [6,13,17]]
k = 1
print("The original list is : "+str(input_list))
# Using list comprehension
ele = [i[k] for i in input_list]
print("The Kth column of matrix using list comprehension : "+str(ele))


# Using zip()
ele1 = list(zip(*input_list))
print("The Kth column of matrix using zip() : "+str(ele1[k]))

Output

Program to find the elements of Kth column Output

Explanation

In the above python code, we have used two ways to find the elements in column2 ( i.e k = 1 as indexing starts from 0): 1. Using list comprehension ; 2. Using zip().

By using list comprehension, all the elements in the list are iterated and the elements at kth index is selectively stored in variable ele.

Similarly, the zip() function returns the values at iterator levels (the values in corresponding passed iterators are stored together). The values passed at iterator 1 is displayed using print (“…” , + str(ele[k])).

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author