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
print name
Output
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
print names
Output
Appending A New Element To Existing One
You can append a new element to existing list. For example
Program Code
print names
names.append("selena holmes")
print names
Output
["lady gaga", "barack obama", "selena holmes"]
Removing an element
For removing an element, you need to know an element you want to remove. Here's the code
Program Code
print names names.remove("barack obama")
print names
Output
["lady gaga", "selena holmes"]
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
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
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]
For Statement In List
It's very easy to iterate all elements in a list using for. Try this code.
Program Code
for item in fruits:
print item
Output
melon
orange
banana
If Statement In List
If statement can be also to test whether a list contain specified element of not.
Program Code
if "shakira" in names:
print "Okey, \"shakira\" existed on names list"
else:
print "Noop, \"shakira\" doesn't exists on names list"
No comments:
Post a Comment