A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

My notes for Lists in Python

Lists

  • A list is a sequence of values.
  • [ and ]
  • like numerically indexed arrays in PHP
>>> # a list of numbers
>>> my_numbers = [10, 15, 20, 25]
>>> print my_numbers
[10, 15, 20, 25]    
>>> 
>>> #a list of strings
>>> my_strings = ['Wenbert', 'Programming', 'Address']
>>> print my_strings
['Wenbert', 'Programming', 'Address']
>>> 
>>> # a list within a list
>>> nested = ['Wenbert', ['PHP','Python','Javascript'], 'Philippines']
>>> print nested, my_numbers
>>>  ['Wenbert', ['PHP','Python','Javascript'], 'Philippines'] [10, 15, 20, 25]
>>>
>>> #Check if "PHP" is in "nested" list
>>> 'PHP' in nested
True
>>> 'Java' in nested
False

To traverse a list:

for item in nested:
    print item

Slicing a list:

>>> basket = ['apples', 'mangoes', 'guava', 'grapes']
>>> basket[2:4]
['guava', 'grapes']

You can append to a list:

>>> basket =  ['apples', 'mangoes', 'guava', 'grapes']
>>> basket.append('banana')
>>> print basket
['apples', 'mangoes', 'guava', 'grapes', 'banana']

You can sort a list:

>>> basket =  ['apples', 'mangoes', 'guava', 'grapes']
>>> basket.sort()
>>> print basket
['apples', 'grapes', 'guava', 'mangoes']

You can “pop”, “delete” and “remove” from a list.

>>> basket =  ['apples', 'mangoes', 'guava', 'grapes']
>>> 
>>> basket.pop()
'grapes'
>>> print basket
['apples', 'mangoes', 'guava']
>>> 
>>> basket.remove('mangoes')
>>> print basket
['apples', 'guava']
>>> 
>>> del basket[0]
>>> print basket
['guava']

Spliting and Joining:

>>> string = 'Wenbert Del Rosario'
>>> pieces = string.split()
>>> print pieces
['Wenbert', 'Del', 'Rosario']
>>>
>>> bag = 'healing potion | dagger | round shield |gold'
>>> items = bag.split(' | ')
>>> print items
['healing potion', 'dagger', 'round shield |gold']
>>> ">".join(items) #glue items together with the ">" symbol
'healing potion>dagger>round shield |gold'

That’s about it. If I encounter more, I will update this post.

This entry was posted in General and tagged , . Bookmark the permalink.

2 Responses to My notes for Lists in Python

  1. How can we pop from the list? I understood everything else except this. Can you help please?

  2. Wenbert says:

    .pop() just returns the last value and then removes it from the list.

    For example:

    >>> letters =  ['a', 'b', 'c', 'd']
    >>> var1 = letters.pop() #var1 will "receive" the last element - "d"
    >>> print var1
    d
    >>> print letters
    ['a', 'b', 'c']

Leave a Reply to Best Design Company Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>