Python | Replace the elements of the list with its ordinal number



Examples :

  Input:  [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]  Output:  [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]]  Input:  [[`a`], [` d`, `e`,` b`, `t`], [` x`, `l`]]  Output:  [[0], [ 1, 1, 1, 1], [2, 2]] 

Approach # 1: The naive approach

This method is a one-line naive approach, in which we use two for loops using the variables i and j, and iterate over each inner list to replace it with i- m with a serial number.

# Python3 element replacement program
# listed with serial number

 

def replaceOrdinal (lst):

  return [[i for j in range ( len (lst [i]))] 

for i in range ( len (lst))]

 
Driver code

lst = [[[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 , 10 ]]

print (replaceOrdinal (lst))

Exit:

 [[0 , 0, 0], [1, 1, 1], [2, 2, 2, 2]] 

Approach # 2: Pythonic Naive

This is another naive approach, but more pythonic . For each inner list, it returns the i- th position (which is its ordinal number) and then multiplies that by the length of that particular inner list to get the desired result.

# Python3 program to replace an element
# in a list with a sequential number

 

def replaceOrdinal (lst):

return [[i] * len (lst [i]) for i in range ( len   (lst))]

 
Code driver

lst = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 , 10 ]]

print (replaceOrdinal (lst) )

Exit:

 [[ 0, 0, 0], [1, 1, 1], [2, 2, 2, 2]] 

Approach # 3: Using Python enumerate () method
We can use list comprehension along with enumerate () Python enumerate () . This method adds a counter to the iterable and returns it in the form of an enumeration object. This counter will be used as a sequence number. And so we return the corresponding counter index for each element of the internal sublist.

# Python3 element replacement program
# in a list with a sequential number

 

def replaceOrdinal (lst):

return [[idx for _ in sublist] 

for idx, sublist in enumerate (lst)]

  
Driver code

lst = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 , 10 ]]

print (replaceOrdinal (lst))

Output:

 [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]] 

Approach # 4: Alternative to use e numerate ()
Here we use Python enumerate () in the same method as in the previous method, but instead of another loop, we follow approach # 4 to get an inner list.

# Python3 element replacement program
# in the list with a serial number

 

def replaceOrdinal (lst):

return [[index] * len (sublist) for index,

  sublist in enumerate (lst)]

 
Driver code

lst = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 , 10 ]]

print (replaceOrdinal (lst))

Exit:

 [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]]