Python List and its Methods
LIST DATA TYPES:
List is a versatile data type exclusive in
Python. In a sense it is same as array in C/C++. But interesting thing about
list in Python is it can simultaneously hold different type of data. Formally
list a ordered sequence of some data written using square brackets([]) and
commas(,).
#list of having only integers
a= [1,2,3,4,5,6]
print(a)
#list of having only strings
b=["hello","john","reese"]
print(b)
#list of having both integers and strings
c=
["hey","you",1,2,3,"go"]
print(c)
#index are 0 based. this will print a
single character
print(c[1]) #this will print
"you" in list c
A subsequence of a sequence is called a
slice and the operation that extracts a subsequence is called slicing. Like
with indexing, we use square brackets ([ ]) as the slice operator, but instead
of one integer value inside we have two, seperated by a colon (:):
>>> singers = "Peter, Paul,
and Mary"
>>> singers[0:5]
'Peter'
>>> singers[7:11]
'Paul'
>>> singers[17:21]
'Mary'
>>> classmates = ["Alejandro",
"Ed", "Kathryn", "Presila", "Sean",
"Peter"]
>>> classmates[2:4]
('Kathryn', 'Presila')
The operator [n:m] returns the part of the
sequence from the n’th element to the m’th element, including the first but
excluding the last. This behavior is counter-intuitive; it makes more sense if
you imagine the indices pointing between the characters, as in the following
diagram:
'banana' string
If you omit the first index (before the
colon), the slice starts at the beginning of the string. If you omit the second
index, the slice goes to the end of the string. Thus:
>>> fruit = "banana"
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
What do you think s[:] means? What about
classmates[4:]?
Negative indexes are also allowed, so
>>> fruit[-2:]
'na'
>>> classmates[:-2]
('Alejandro', 'Ed', 'Kathryn', 'Presila')
Tip
Developing a firm understanding of how
slicing works is important. Keep creating your own “experiments” with sequences
and slices until you can consistently predict the result of a slicing operation
before you run it.
When you slice a sequence, the resulting
subsequence always has the same type as the sequence from which it was derived.
This is not generally true with indexing, except in the case of strings.
>>> strange_list = [(1, 2), [1,
2], '12', 12, 12.0]
>>> print(strange_list[0],
type(strange_list[0]))
(1, 2) <class 'tuple'>
>>> print(strange_list[0:1],
type(strange_list[0:1]))
[(1, 2)] <class 'list'>
>>> print(strange_list[2],
type(strange_list[2]))
12 <class 'str'>
>>> print(strange_list[2:3],
type(strange_list[2:3]))
[12] <class 'list'>
List
Methods
Here are some other common list methods.
list.append(elem) -- adds a single element
to the end of the list. Common error: does not return the new list, just
modifies the original.
list.insert(index, elem) -- inserts the
element at the given index, shifting elements to the right.
list.extend(list2) adds the elements in
list2 to the end of the list. Using + or += on a list is similar to using
extend().
list.index(elem) -- searches for the given
element from the start of the list and returns its index. Throws a ValueError
if the element does not appear (use "in" to check without a
ValueError).
list.remove(elem) -- searches for the
first instance of the given element and removes it (throws ValueError if not
present)
list.sort() -- sorts the list in place
(does not return it). (The sorted() function shown below is preferred.)
list.reverse() -- reverses the list in
place (does not return it)
list.pop(index) -- removes and returns the
element at the given index. Returns the rightmost element if index is omitted
(roughly the opposite of append()).
Notice that these are *methods* on a list
object, while len() is a function that takes the list (or string or whatever)
as an argument.
list = ['larry', 'curly', 'moe']
list.append('shemp') ##
append elem at end
list.insert(0, 'ele') ##
insert elem at index 0
list.extend(['yyy', 'zzz']) ##
add list of elems at end
print list ## ['ele', 'larry',
'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly') ## 2
list.remove('curly') ##
search and remove that element
list.pop(1) ##
removes and returns 'larry'
print list ## ['ele', 'moe',
'shemp', 'yyy', 'zzz']
Common error: note that the above methods
do not *return* the modified list, they just modify the original list.
list = [1, 2, 3]
print list.append(4) ## NO, does
not work, append() returns None
##
Correct pattern:
list.append(4)
print list ## [1, 2, 3, 4]
List Build Up
One common pattern is to start a list a the
empty list [], then use append() or extend() to add elements to it:
list = [] ## Start as the
empty list
list.append('a') ## Use append()
to add elements
list.append('b')
Comments
Post a Comment