List concept in Python

It is a list of comma separated values in square brackets. >>> x = [‘Hello’, 10, ‘World’, ’20’] >>> print x [‘Hello’, 10, ‘World’, ’20’]

First element in the list starts at 0 index. >>> x[0] ‘Hello’

>>> type(x) # function type() specifies type of an object.

<type ‘list’> # x is of type list

 

>>> x[-1]

’20’

>>> x[-2]

‘World’

List can have items of different types unlike in C/C++ where we can have array of only single type.

Lists can be sliced, concatenated and so on: >>> x[:2] #list sliced to display first two elements

[‘Hello’, 10]

 

>>> x[:-1]

[‘Hello’, 10, ‘World’] # list sliced to drop 2 elements

>>> x[:1] + [‘Good Morning’] # Concatenate 2 lists

[‘Hello’, ‘Good Morning’]

Apart, from this you have several other in-built methods like append, count, extend, reverse, pop, etc to add, delete, count items, etc.

>>> x.append(40)

>>> x

[‘Hello’, 10, ‘World’, ’20’, 40]

• Unlike strings, which are immutable, it is possible to change individual elements of a list:

>>> a

[‘Hello’, 10, ‘World’, ’20’]

>>> x[1] = x[1] + 23

>>> print x [‘Hello’, 33, ‘World’, ’20]

Leave a Reply

Your email address will not be published. Required fields are marked *