workonfire
workonfire

Reputation: 11

How to join two items in a Python list?

I have this:

list = ['h', 'e', "'", 'l', 'l', 'o']

And I want to have this:

list = ['h', "e'", 'l', 'l', 'o']

I want to join only two list elements. How can I do that?

Upvotes: 0

Views: 803

Answers (5)

user9158931
user9158931

Reputation:

You can filter the result what you want :

Never use list as variable name :

list_1 = ['h', 'e', "'", 'l', 'l', 'o']

print(list(filter(lambda x:x!="'",list_1)))

output:

['h', 'e', 'l', 'l', 'o']

if you want to join then :

print("".join(list(filter(lambda x:x!="'",list_1))))

output:

hello

Upvotes: 1

Artier
Artier

Reputation: 1673

Try this

>>> li=list("He'llo")
>>> li[2:4]=[''.join(li[2:4])]
>>> li
['H', 'e', "'l", 'l', 'o']

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71461

You can use unpacking in Python3:

l = ['h', 'e', "'", 'l', 'l', 'o']
a, *b, c, d, e = l
new_l = [a, ''.join(b), c, d, e]

Output:

['h', "e'", 'l', 'l', 'o']

Since Python2 does not support list unpacking (*), you can use list slicing:

l = ['h', 'e', "'", 'l', 'l', 'o']
new_l = l[:1]+[''.join(l[1:3])]+l[3:]

Output:

['h', "e'", 'l', 'l', 'o']

Upvotes: 4

Jakob Lovern
Jakob Lovern

Reputation: 1341

As John Gordon stated in comments, the simplest way to do it would probably be like so:

l = list("he'llo")
l[1] += l[2]
del l[2]

Upvotes: 2

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

You could define your own function and use .pop to remove the second element:

def merge(myList, a, b):
    myList[a] = myList[a] + myList.pop(b)
    return myList

>>> merge(['h', 'e', "'", 'l', 'l', 'o'], 1, 2)
['h', "e'", 'l', 'l', 'o']

Upvotes: 1

Related Questions