FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

Python Lists: Assigning and deleting elements




Assigning an element in a Python list is quiet intuitive and works basically the same like accessing array elements in most other programming languages, like so:
Code:

>>> list = ["one", "two", "three", "four", "five"]
>>> list
['one', 'two', 'three', 'four', 'five']
>>> list[1]
'two'

This way we also easily can change a particular list element:
Code:

>>> list[1] = 2
>>> list
['one', 2, 'three', 'four', 'five']

Deleting a list element is done using the del statement:
Code:

>>> del list[1]
>>> list
['one', 'three', 'four', 'five']

Slicing can be used to access part of a list:
Code:
>>> list[1:] = [3,4,5]
>>> list
['one', 3, 4, 5]

This means we can also use slicing to delete an arbitrary part of a list:
Code:

>>> list[1:] = []
>>> list
['one']




1 blog comments below

Don't forget the slicing and indexing can also be done from the end of a list by using negative indexes. For example, to get the last element in an array:

Code:
last = MyList[-1]
LuskeyNoah on Wed Dec 18, 2013 12:55 am



FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.