Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over lists of lists in Python

I have a list of lists:

lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]

I want to iterate over each element and perform some string operations on them for example:

replace("(", "")

I tried iterating over the list using:

for l1 in lst1:
   for i in l1:
       lst2.append(list(map(str.replace("(", ""), l1)))

I wanted the out result to be the same as original list of lists but without the parenthesis. Also, I am looking for a method in editing lists of lists and not really a specific solution to this question.

Thank you,

like image 885
konrad Avatar asked Jan 23 '26 12:01

konrad


1 Answers

Edit:

Yes, you should use normal for-loops if you want to:

  1. Preform multiple operations on each item contained in each sub-list.

  2. Keep both the main list as well as the sub-lists as the same objects.

Below is a simple demonstration of how to do this:

main = [["(a)", "(b)", "(c)"], ["(d)", "(e)", "(f)", "(g)"]]

print id(main)
print id(main[0])
print id(main[1])
print

for sub in main:
    for index,item in enumerate(sub):

        ### Preform operations ###
        item = item.replace("(", "")
        item = item.replace(")", "")
        item *= 2

        sub[index] = item  # Reassign the item

print main
print
print id(main)
print id(main[0])
print id(main[1])

Output:

25321880
25321600
25276288

[['aa', 'bb', 'cc'], ['dd', 'ee', 'ff', 'gg']]

25321880
25321600
25276288

Use a nested list comprehension:

>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> id(lst1)
35863808
>>> lst1[:] = [[y.replace("(", "") for y in x] for x in lst1]
>>> lst1
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]
>>> id(lst1)
35863808
>>>

The [:] will keep the list object the same.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!