7

Let's say I have a list:

list = ["word", "word2", "word3"]

and I want to change this list to:

list = ["word:", "word2:", "word3:"]

is there a quick way to do this?

hacktheplanet
  • 105
  • 1
  • 1
  • 3

3 Answers3

15

List comprehensions to the rescue!

list = [item + ':' for item in list]

In a list of

['word1', 'word2', 'word3'] 

This will result in

['word1:', 'word2:', 'word3:']

You can read more about them here.

https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

ollien
  • 4,418
  • 9
  • 35
  • 58
5

You can use a list comprehension as others have suggesed. You can also use this code:

newlist = map(lambda x: x+':', list)
Traxidus Wolf
  • 808
  • 1
  • 9
  • 18
pad
  • 2,296
  • 2
  • 16
  • 23
  • 1. you should not use the word list as a variable name because it represents python type 2. map does not return a list , type(newlist)== – sagi Apr 25 '20 at 13:57
0

simple question but though a noob friendly answer :)

list = ["word", "word2", "word3"]
n = len(list)
for i in range(n):
    list[i] = list[i] + ':'

print list 

strings can be concatenated using '+' in python and and using 'len' function you can find the length of list. iterate i using for loop till n and concatenate ':' to the list eliments. feel free to post but thing of google first :P

kedarkhetia
  • 101
  • 9