How To Add Data In List Below?
Solution 1:
You can iterate over the list and extend it with the reversed elements:
List = [[['1','2'],['2','4']],[['1','4'],['4','8']],[['53','8'],['8','2'],['2','82']]]
for sublist in List:
sublist.extend([pair[::-1] for pair in sublist])
In the end, List
will be:
[[['1', '2'], ['2', '4'], ['2', '1'], ['4', '2']],
[['1', '4'], ['4', '8'], ['4', '1'], ['8', '4']],
[['53', '8'], ['8', '2'], ['2', '82'], ['8', '53'], ['2', '8'], ['82', '2']]]
Solution 2:
You can use a nested list comprehension that iterates over the sub-lists and reverses sub-lists within, before merging them with the original sub-lists:
[l + [s[::-1] for s in l] for l in List]
Solution 3:
While this answer may not be the most Pythonic of answers given the original intent of the function I use was for reverse iteration over sequences. This accomplishes your goal in a concise, readable fashion, imho.
I have made use of the function reversed()
. This function will return a reverse-order list_reverseiterator
object based on your original list. Considering this returned object is not a list, we can use the list
type change function as such: list(reversed(List))
and this will provide you with the reversed original list. Then, the original candidate List
is appended with the newly reversed list to create the desired output you had requested.
List = [[['1','2'],['2','4']],[['1','4'],['4','8']],[['53','8'],['8','2'],['2','82']]]
print("Here is the original list: ", List)
ListReverse = list(reversed(List))
List.append(ListReverse)
print("Here is your final list: ", List)
While the print statements are accessory to the original ask, I have included them so you have a verification of the working solution.
Post a Comment for "How To Add Data In List Below?"