GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Sunday, May 8, 2011

Python - List

Introduction

List is a data structure in Python. It's like an array in other programming languages. But list in Python is more powerful, because it can contain different data type.

Program Code

name = ["lady gaga", "luna maya", "aura kasih"]
print name

Output

["lady gaga", "luna maya", "aura kasih"]

How To

For declaring the list, you use like the above, then you wrap it with square bracket. You can also make an empty list

Program Code

names = []
print names

Output

[]

Appending A New Element To Existing One

You can append a new element to existing list. For example

Program Code

names = ["lady gaga", "barack obama"]
print names
names.append("selena holmes")
print names

Output

["lady gaga", "barack obama"]
["lady gaga", "barack obama", "selena holmes"]
From the above you see that the append() method will add a new element to the last one. "selena holmes" added to the list.

Removing an element

For removing an element, you need to know an element you want to remove. Here's the code

Program Code

names = ["lady gaga", "barack obama", "selena holmes"]
print names names.remove("barack obama")
print names

Output

["lady gaga", "barack obama", "selena holmes"]
["lady gaga", "selena holmes"]
You see that there's nothing the name for "barack obama".

Slicing

Slicing is one of the most usefule feature of list. Slicing means that when you just need some data you can do it with less of the code.

Program Code

ages = [10, 20, 30, 40, 50]
print ages
print "exclude the first one: ", ages[1:]
print "exclude the first three: ", ages[3:]
print "just the first one: ", ages[:1]
print "just from 1st till less than 3rd: ", ages[1:3]

Output

[10, 20, 30, 40, 50]
exclude the first one: [20, 30, 40, 50]
exclude the first three: [40, 50]
just the first one: [10]
just from 1st till less than 3rd: [20, 30]
Keep in mind that the slicing index started from zero. It need sometime to understand this one, but when you have master it, you can make manuver.

For Statement In List

It's very easy to iterate all elements in a list using for. Try this code.

Program Code

fruits = ["apple", "melon", "orange", "banana"]
for item in fruits:
    print item

Output

apple
melon
orange
banana

If Statement In List

If statement can be also to test whether a list contain specified element of not.

Program Code

names = ["lady gaga", "madonna", "selena holmes", "avril"]
if "shakira" in names:
    print "Okey, \"shakira\" existed on names list"
else:
    print "Noop, \"shakira\" doesn't exists on names list"

Output

Noop, "shakira" doesn't exists on names list


Share/Bookmark

No comments:

Post a Comment