Python Forum

Full Version: Indexed position editing of a lst
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I have a list say suppose,
list= [Mysore,Bangalore,chennai,pune]

In this I want to edit the list like,
edited_list=[Mysore is a beautiful city,Bangalore,chennai,pune]

How can we do this,I tried different methods like insert,append,extend. But that didn't work.
Is there any python inbuilt module. Or how can we do this indexed position editing.

Thank you,
Shruthi LS
Never use 'list' as name (this is built-in function).

What is the problem? Access items in list?

>>> lst = ['Mysore','Bangalore','chennai','pune']
>>> lst[0]
'Mysore'
Ya thank you for the reply. But how can I edit by adding something to the zeroth position i.e., Mysore in this example. May it be anything.
just use assignment
>>> my_list = ['foo', 'bar']
>>> my_list[0] = 'spam'
>>> my_list
['spam', 'bar']
>>> my_list = [1, 2, 3, 4]
>>> my_list[1:3] = [5, 6]
>>> my_list
[1, 5, 6, 4]
If its about string replacement then there can be different scenarios:

(1) Replace one item in list (use assignment as suggested by buran):

>>> foods = ['ham', 'spam']
>>> foods[0] = ' '.join([foods[0], 'and eggs'])
>>> foods
['ham and eggs', 'spam']
(2) Replace all values, same text:

>>> foods = ['ham', 'spam']
>>> foods = [' '.join([food, 'and eggs']) for food in foods]
>>> foods
['ham and eggs', 'spam and eggs']
(3) Replace all values, different text:

>>> foods = ['ham', 'spam']
>>> add_ons = ['and eggs', 'and spam']
>>> foods = [' '.join(pair) for pair in zip(foods, add_ons)]
>>> foods
['ham and eggs', 'spam and spam']