1

If i had a list e.g.

['Hello', 'what', 'is', 'your', 'name'] 

what method lets you move the position of a character within the item itself and store it. So 'Hello' could be changed to 'elloH' by moving first character to the end and the same applied to rest of the items.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Programmer
  • 35
  • 7

3 Answers3

2

You could use slicing and indexing:

def shift(s):
    return s[1:] + s[0]

data = ['Hello', 'what', 'is', 'your', 'name']

result = [shift(s) for s in data]

print(result)

Output

['elloH', 'hatw', 'si', 'oury', 'amen']

The statement result = [shift(s) for s in data] is known as a list comprehension, is the equivalent of the following:

result = []
for s in data:
    result.append(shift(s))

Finally another alternative is to use map:

result = list(map(shift, data))

The function map applies shift to each element of data, but it returns (in Python 3) an iterable so you need to convert it to list.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
2

just rebuild the list and generate new strings with slicing & addition:

lst = ['Hello', 'what', 'is', 'your', 'name']

result = [x[1:]+x[0] if x else "" for x in lst]

result:

['elloH', 'hatw', 'si', 'oury', 'amen']

(note the ternary expression which allows robustness to empty strings, since int the case of empty strings x[0] would raise an IndexError. Without a ternary expression, we could use [x[1:]+x[0:1] for x in lst] which does the same thing)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

Check the below code :

mylist = ['Hello', 'what', 'is', 'your', 'name']

mylist = [(mylist[i][1:] + mylist[i][0:1]) for i in range(0,len(mylist))]

print(mylist)

Output :

['elloH', 'hatw', 'si', 'oury', 'amen']
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19