Lists in Python

✓ List – It is a sequence of values. The values in a list are called elements/ items. Lists are mutable.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> print cheeses
['Cheddar', 'Edam', 'Gouda']
>>>  = [17, 123]
>>> print numbers
[17, 123] 
>>> empty = []
>>> print empty
[]

>>> print cheeses[0]
Cheddar

>>> numbers = [17, 123]
>>> numbers[1] = 5 #list are mutable
>>> print numbers
[17, 5]

✶ List indices work the same way as string indices.
✶ Any integer expression can be used as an index.
✶ If you try to read or write an element that does not exist, you get an IndexError.
✶ If an index has a negative value, it counts backward from the end of the list.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

for cheese in cheeses:
print cheese

✓ List operations

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> print a+b
[1, 2, 3, 4, 5, 6]

# sorting
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> print t.sort()
['a', 'b', 'c', 'd', 'e']

✓ Map, filter, and reduce operations

>>> t = [1, 2, 3]
>>> sum(t)
6

#Capitalizing all the elements
def capitalize_all(t):
    res = []
    for s in t:
       res.append(s.capitalize())
    return res

#Selecting only capital elements
def only_upper(t):
    res = []
    for s in t:
        if s.isupper():
            res.append(s)
    return res

✓ Deleting elements

>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']

✓ Lists and strings

#Convert string to list of characters
>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']

#Convert sring to list of words
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']

>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

✓ List aliasing

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

#If a change made on one alias, that will affect other as well
>>> b[0] = 17
>>> print a
[17, 2, 3]

✓ List as argument

def delete_head(t):
   del t[0]

>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s