Python Programming for Biology: Bioinformatics and Beyond


List and tuple manipulation



Download 7,75 Mb.
Pdf ko'rish
bet38/514
Sana30.12.2021
Hajmi7,75 Mb.
#91066
1   ...   34   35   36   37   38   39   40   41   ...   514
Bog'liq
[Tim J. Stevens, Wayne Boucher] Python Programming

List and tuple manipulation

In  this  section  we  will  illustrate  some  basic  manipulations  on  tuples  and  lists  using  the

following tuple and list examples to do this:

t = (123, 54, 92, 87, 33) # tuple

x = [123, 54, 92, 87, 33] # list

When  you  need  to  fetch  a  value,  from  a  tuple  or  list,  the  items  are  accessed  by  their

index number: the position of the desired item relative to the start. Although Python uses

round parentheses to define tuples and square brackets to define lists, when you want to

access an item of a tuple or list, in both cases you use square brackets, i.e. myList[index],

myTuple[index] will fetch the value at the index position of the list and tuple respectively.

Note  that  the  index  for  accessing  items  of  tuples  and  lists  starts  counting  from  0,  not  1.

Thus the first item of a tuple or list is the element with index 0. By way of example, here

we obtain the first item of the above defined tuple and the third element of the list:

t[0] # 123

x[2] # 92

Python  also  lets  you  access  items  starting  from  the  end  of  the  tuple  or  list  using

negative indices, where the index -1 refers to the last item, -2 to the next-to-last etc.

t[-1] # 33

x[-3] # 92

If  the  tuple  or  list  has  n  items,  then  the  minimum  value  of  the  index  is  –n  and  the

maximum value is n-1. If the index falls outside this range an error is generated; Python



makes  an  Exception  object  which  reports  what  the  error  was  (see  the  next  chapter  for  a

description  of  these).  As  with  strings,  Python  has  a  very  convenient  slicing  notation,  to

access a range of items from within a tuple or list. The notation [start:stop]  refers  to  the

items  from  position  start  up  to  but  not  including  position  stop.  As  with  single  indices,

these positions can be negative.

As a further convenience, if you leave out the start entirely giving just [:stop], then the

slice starts at the very beginning; the start point is taken to be 0. If you leave out the stop,

so  have  [start:],  then  the  slice  continues  to  the  very  end;  as  if  stop  were  taken  to  be  the

length of the tuple or list. Thus, for example, [:n] refers to the first n items of the tuple or

list. If you leave out both the start and stop points then you get back a copy of the original

tuple or list, and this is a convenient way of doing that.

t[1:3] # (54, 92)

t[1:] # (54, 92, 87, 33)

x[1:-1] # [54, 92, 87]

x[:-1] # [123, 54, 92, 87]

x[:] # [123, 54, 92, 87, 33] – A copy

You can check if an item is present inside a tuple or list by using the in operator, which

gives you back a Boolean value (true or false):

92 in t # True

93 in x # False

Similarly you can also check if an item is not within a tuple or list:

92 not in t # False

93 not in x # True

Neither  of  these  is  a  particularly  efficient  operation  (computationally),  so  for  long

tuples and lists you may want to avoid doing too many of this kind of check if possible.

With checks of this kind to be more efficient you would often use sets.

For lists and tuples you can count the number of occurrences of an item, which may be

more useful than simply detecting its presence:

y = [3, 11, 7, 3]

y.count(3) # 2

For lists you can check at which index a given item is located, noting that this gives the

first occurrence if there is more than one:

x.index(87) # 3

The index() function also exists for tuples in versions of Python from 2.6 onwards (it is

slightly  odd  that  it  took  Python  so  long  to  introduce  it).  Using  index()  is  also  not  very

computationally  efficient,  although  it  is  not  often  needed.  The  len()  function  returns  the

number of items in the tuple or list; its length in other words:

len(t) # 5

len(x) # 5



So far we have been discussing how to access the items in a tuple or list. Tuples are not

modifiable so the above is pretty much the end of the story for them. However, given that

lists are modifiable there are more things we need to consider. You can change the item at

a specific position in the list:

x[1] = 55 # x now [123, 55, 92, 87, 33]

If you mistakenly tried the same operation on a tuple you would get an error:

t[1] = 55 # Fails!

TypeError: 'tuple' object does not support item assignment

You can append new items to the end of a list:

x.append(17) # x now [123, 55, 92, 87, 33, 17]

You can add a list’s items on to the end of another:

y = [1, 2]

y.extend(x) # y now [1, 2, 123, 55, 92, 87, 33, 17]

You can insert items at specific positions:

x.insert(1, 99) # x now [123, 99, 55, 92, 87, 33, 17]

Here,  for  example,  the  index  of  1  indicates  what  its  final  position  will  be  after  the

insertion; it is inserted before the previous item at position 1. And if the index is the length

of  the  list  then  the  insertion  is  after  the  last  existing  item,  which  is  equivalent  to  using

append. Strangely, if the index is less than 0 it acts as if it were 0, inserting before the first

item.  Similarly,  any  index  greater  than  the  length  of  the  list  inserts  after  the  last  item.

Either way, no error is triggered for having an out-of-range index.

You can remove a specific item from within the list, thus shortening it:

x.remove(92) # x now [123, 99, 55, 87, 33, 17]

This  will  cause  an  error  if  the  item  is  not  in  the  list.  You  can  also  delete  an  item  at  a

specific position with the del statement:

del x[4] # x now [123, 99, 55, 87, 17]

This  will  cause  an  error  if  the  index  is  out  of  range.  Lists  also  have  a  pop()  method

which  allows  you  to  remove  (‘pop  out’)  the  item  at  a  particular  index,  but  this  function

will also return the value of the item, rather than discarding it entirely:

y = x.pop(2) # x now [123, 99, 87, 17], y is 55

You can even change a range of items of a list to a new range of items using the slice

notation, although this takes some getting used to:

x[1:3] = [19, 21, 5] # x now [123, 19, 21, 5, 17]

This has replaced two items, at positions 1 and 2, with three new items.

You can reverse the order of the items in a list:



x.reverse() # x now [17, 5, 21, 19, 123]

Also, lists can be sorted internally using the sort() function:

x.sort() # x now [5, 17, 19, 21, 123]

If you want a new list to be generated as a result of the sorting, rather than the original

list being altered, then you can use the sorted() function:

x = [123, 54, 92, 87, 33]

y = sorted(x) # y = [33, 54, 87, 92, 123], x unchanged

Note the difference in syntax, so there is no sort(x) and also no x.sorted().  In  fact  the

sorted() function can also be used on tuples and sets, but still returns a new list:

t = (123, 54, 92, 87, 33)

y = sorted(t) # y = [33, 54, 87, 92, 123], t unchanged

The sort() and sorted() functions use the ‘natural’ sort order of the items; numeric and

alphabetic. However, it is possible to specify another ordering method, for example, to get

the reverse of the sort. These topics are covered in

Chapter 5

on functions.




Download 7,75 Mb.

Do'stlaringiz bilan baham:
1   ...   34   35   36   37   38   39   40   41   ...   514




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish