1

I am new in programming and Python. I have a list in my hand and I want to manipulate my list as each words will be consisted of (first) 6 letters maximum.

Sample list as below.

 new_list = ['partiye', 'oy', 'vermeyecegimi', 'bilerek', 'sandiga', 'gidecegim']

I used below code for cutting the words.

 s = []
 a = []
 for i in range(len(new_list)):
      s = new_list[i]
      for j in new_list:
           a = s[:6]     
 print a 

Each words consist of max 6 letters. The output of the code is "partiy oy vermey bilere sandig gidece".

But I could not assign my updated (cutted) words into a new list. Can someone advise me how can I do that ?

1 Answer 1

3

This is where list comprehensions become really handy:

>>> new_list = ['partiye', 'oy', 'vermeyecegimi', 'bilerek', 'sandiga', 'gidecegim']
>>> print [i[:6] for i in new_list]
['partiy', 'oy', 'vermey', 'bilere', 'sandig', 'gidece']

If you wanted to expand it:

s = []
for i in new_list:
    s.append(i[:6])

It's pretty much the same approach as what you're doing, but it's a little neater.

What you're doing is continually re-assigning a to a value so it's rather pointless. I think you wanted a.append(s[:6]) anyway, which adds a value to a list, but even then that won't work since you're approaching the solution the wrong way :p.

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

3 Comments

Terry, but the list is not updated. new_list is still as below isn't it ? I also want to update my list as each words will be max 6 letters. 'code' >>> new_list = ['partiye', 'oy', 'vermeyecegimi', 'bilerek', 'sandiga', 'gidecegim']
@Behzat That's because the list comprehension does not override the list, you need to do that. This is easily obtained by doing new_list = [i[:6] for i in new_list]
Many thanks Terry. That's what I try to do. It works very well.

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.