Home > Back-end >  join two consecutive list elements
join two consecutive list elements

Time:04-27

i have a list names that looks like this

names = ['Peter Orson', 'Marc Johnson', 'Peter', 'Johnson']

i want to join two specific elements of that list.

desired_names = ['Peter Orson', 'Marc Johnson', 'Peter Johnson']

caveat:

  1. i cannot use index
  2. i need to target only these two individual elements even though other elements share some parts (e.g. same first name)

code:

regex = re.compile(r'/^Peter$/)
for i in names:
    if regex:
        i = ' '.join(map(str, regex)) # join with next list element into one string

I think i have the right approach to my problem but i dont know how to join and replace the matched string elements

CodePudding user response:

As stated in the comments, you don't need the regex to do that:

names = [
    "Peter Orson",
    "Marc Johnson",
    "Peter",
    "Johnson",
]

idx = names.index("Peter")
names[idx] = names.pop(idx)   " "   names[idx]
print(names)

Prints:

['Peter Orson', 'Marc Johnson', 'Peter Johnson']

If you aren't sure if "Peter" is in the list, you can check before:

if "Peter" in names:
    idx = names.index("Peter")
    names[idx] = names.pop(idx)   " "   names[idx]
  • Related