0

For example lets say I have a list ['this', 'is', 'a', 'test'] and another list as ['i','t','t','a'] and I want to produce ['ihis', 'ts', 't', 'aest']. I tried to do a for loop but it would not let me delete anything because it is immutable.

I tried:

for i in list1: del i[0]
2
  • 1
    the fourth element of the result is aest right? Commented Apr 2, 2018 at 1:19
  • yes, my bad i changed it Commented Apr 2, 2018 at 1:24

4 Answers 4

1

Yes, strings are immutable in Python. That means you have to build a new string to replace the old one. And you have to store that new string—either back in the original list, or in a new list.

If you want to store them back in the original list, you need the index as well as the value:

for idx, i in enumerate(list1):
    list[idx] = i[1:]

If you want to create a new list, you just append them as they come in, or use a comprehension:

list2 = []
for i in list1:
    list2.append(i[1:])

list2 = [i[1:] for i in list1]

Usually creating a new list is better (which is why Python has a syntactic shortcut for only that one), but sometimes mutating in-place is better (which is why that one isn't too much more verbose or difficult). The question is: If any other piece of code had made another reference to list1, would you want it to see the changed version, or the original version?

Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with a list comprehension like this:

test_list = ['this', 'is', 'a', 'test']

first_letters = ['i','t','t','a']

[letter+word[1:] for letter, word in zip(first_letters, test_list)]

# ['ihis', 'ts', 't', 'aest']

The zip function essentially creates this list of tuples (it's actually an iterator of tuples, but for simplicity, it can be thought of as a list):

[('i', 'this'), ('t', 'is'), ('t', 'a'), ('a', 'test')]

Which the list comprehension iterates through, returning a new list with the letter (first element of each tuple) and all letters starting from the second letter of the word (second element of the tuple)

It is essentially equivalent to the following loop, if you prefer that syntax:

result = []

for letter, word in zip(first_letters, test_list):
    result.append(letter+word[1:])

Comments

0

you can try range method :

test_list = ['this', 'is', 'a', 'test']

first_letters = ['i','t','t','a']



print([first_letters[i]+test_list[i][1:]for i in range(len(test_list))])

output:

['ihis', 'ts', 't', 'aest']

Comments

-1
x = ['this', 'is', 'a', 'test']
y = ['i','t','t','a']
z = [y + x[1:] for x, y in zip(x, y)]
print(z)

z = ['ihis', 'ts', 't', 'aest']

1 Comment

You can use unpack on each element of zip result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.