3

I tried to substitute elements in a list

# the raw data 
square = ['(', ')', '.', '^', '-']
# the result I want
square = ['[', ']', '.', '^', '-']

with multiple steps using methods of remove and insert

    In [21]: square.remove('(')
    In [22]: square.remove(')')
    In [23]: square.insert(0, '[')
    In [24]: square.insert(1, ']')
    In [25]: square
    Out[25]: ['[', ']', '.', '^', '-']

How to resolve such a problem in a straigtforward way?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • Possible duplicate of [finding and replacing elements in a list (python)](https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list-python) – moooeeeep Mar 26 '18 at 08:52

3 Answers3

11

Dictionaries are great for this kind of thing. Use a list comprehension to iterate through and look up each element in the replacements dictionary, using .get so that it defaults to the current item.

replacements = {'(': '{', ')': '}'}
square = [replacements.get(elem, elem) for elem in square]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
5

The simplest solution, if you know precisely the index of elements you want to change, is using list indexes:

square = ['(', ')', '.', '^', '-']

square[0] = '['
square[1] = ']'

print square

>>> ['[', ']', '.', '^', '-']

On the other hand, if you're not sure about your brackets' position in the list you can use enumerate() and in a single loop you will be able to access both indexes and values of the elements you cycle:

square = ['(', ')', '.', '^', '-']

for index, element in enumerate(square):
    if element == '(':
        square[index] = '['
    if element == ')':
        square[index] = ']'

print square

>>> ['[', ']', '.', '^', '-']

Those are, in my opinion, the most straightforward ways.

The next step, if I can suggest, is to be more Pythonic using lists (and / or dictionaries) comprehension.

Check the jewel in the answer from Daniel Roseman to get an idea.

Pitto
  • 8,229
  • 3
  • 42
  • 51
2
dict_ = {'(':'[',')':']'}
data = [dict_[val] if val in dict_ else val for val in square ]
>>>['[', ']', '.', '^', '-']

with using re module:

import re

print(list(re.sub(r'\(\)','\[\]',''.join(square))))
>>>['[', ']', '.', '^', '-']
Veera Balla Deva
  • 790
  • 6
  • 19