Python Lists

Gauloran

Kıdemli Moderatör
7 Tem 2013
8,119
599
local
[FONT=&quot]Hi, in this article I'm going to talk about Python Lists. Python list is a collection of elements and based on array. Python enables you to put any type of object into the same list and the size of the list is expanded automatically ( behind the scenes ) so that you don't need to worry.
[/FONT]
[FONT=&quot]Everything starts with the square brackets[/FONT][FONT=&quot] [][/FONT]

[FONT=&quot]Lets start with a basic example. Let's say we have a sentence.
[/FONT]
Kod:
[COLOR=Silver]>>> words = ['Python','is','awesome'][/COLOR]
[FONT=&quot]or [/FONT][FONT=&quot]list(iterable)[/FONT][FONT=&quot] which can also convert other types of iterable objects(sequences) into a list[/FONT]
[FONT=&quot]
[/FONT]

Kod:
>>> list.__doc__
  """list() -> new empty list
  list(iterable) -> new list initialized from iterable's items"""
  >>> list((1,2,3)) # a tuple converted into a list
  [1, 2, 3]
  >>> list({"a":1,"b":2}) # dictionary converted to a list
  ['a', 'b']
  >>> list(xrange(10)) # a generator converted/transformed into a list
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[FONT=&quot]
[/FONT]
[FONT=&quot]Append[/FONT]
[FONT=&quot]list.append()[/FONT][FONT=&quot] adds a new element to the end of the list. Since Python list is dynamically sized, we don't need to think about the length of the list. List will keep on extending itsself.
[/FONT]
Kod:
[COLOR=silver]>>> words.append("!")
  >>> words
  ['Python','is','awesome','!'][/COLOR]
[FONT=&quot]
[/FONT]
[FONT=&quot]Length[/FONT]
[FONT=&quot]Lets find out how many elements do we have in our list.. Python builtin function[/FONT][FONT=&quot]len()[/FONT][FONT=&quot] helps us as always[/FONT]

Kod:
>>> len(words)
  4
[FONT=&quot]
[/FONT]
[FONT=&quot]Insert[/FONT]
[FONT=&quot]list.insert(********, element)[/FONT][FONT=&quot] inserts the elemented into the given ********. If the ******** is larger than the number of elements, inserts the element to the last position.[/FONT]

Kod:
>>> words = ['Python','is','awesome']
  >>> words.insert(12, 'hosting')
  >>> words
  ['Python', 'is', 'awesome', 'hosting']
  >>> words = ['Python','is','awesome']
  >>> words.insert(1, 'hosting')
  >>> words
  ['Python', 'hosting', 'is', 'awesome']
  >>> words
  ['Python', 'hosting', 'is', 'awesome']
[FONT="]Pop[/FONT][/B][/COLOR]
[FONT="]Deletes the last element from the list and returns it.
[/FONT]
Kod:
>>> words = ['Python','is','awesome','hosting']
  >>> words.pop()  # remove the added hosting, pop used
  'hosting'
  >>> words
  ['Python','is','awesome']
[FONT=&quot]
[/FONT]
[FONT=&quot]Delete[/FONT]
[FONT=&quot]Builtin [/FONT][FONT=&quot]del[/FONT][FONT=&quot] command helps to remove an element[/FONT]

Kod:
>>> words = ['Python','is','awesome']
  >>> words.append("testing")
  >>> words
  ['Python','is','awesome','testing']
  >>> del words[-1] # Returns None. Check the next section to understand -1..
  >>> words
  ['Python','is','awesome']
[FONT=&quot]Combine two or more lists[/FONT]
[FONT=&quot]You can use[/FONT][FONT=&quot]+[/FONT][FONT=&quot] operator to combine lists. None of the given lists are effected from the operation, a new list created. It's a costy operation. Use wisely.[/FONT]

Kod:
>>> go_words = [ 'Go', 'is', 'also', 'nice']
  >>> words + "," + go_words
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  TypeError: can only concatenate list (not "str") to list
  >>> words + ["."] + go_words  # Don't use this code
Kod:
[COLOR=Plum]['Python', 'is', 'awesome', '.', 'Go', 'is', 'also', 'nice'][/COLOR]
[FONT=&quot]
[/FONT]
[FONT=&quot]Extend[/FONT]
[FONT=&quot]list.extend(sequence)[/FONT][FONT=&quot] adds the given sequence ( list is also a sequence ) to the actual list. The return of the call is [/FONT][FONT=&quot]None[/FONT]

Kod:
>>> words = ['Python','is','awesome']
  >>> go_words = [ 'Go', 'is', 'also', 'nice']
  >>> words.extend(go_words)
  >>> words
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice']
  >>> words.extend((1,2,3))
  >>> words
Kod:
[COLOR=Plum]   ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3][/COLOR]


[FONT=&quot]Be careful[/FONT]

Kod:
>>> words = words.extend([1,2,3])
  >>> words
  >>> len(words)
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
   TypeError: object of type 'NoneType' has no len()


[FONT=&quot]Nothing is printed, because our list became a None (Object). [/FONT][FONT=&quot]words[len(words)-1][/FONT][FONT=&quot] is not the preffered way. Because we can use -1 If you are going to built a programming language, please implement this as a must-to-have. Java, C#, javascript don't have this feature. I still cannot understand, wtf?![/FONT]

Kod:
>>> words[-1]
  'awesome'
  >>> words[-2]
  'is'
  >>> words[-3]
   'Python'
[FONT=&quot]Slicing - Sublist[/FONT]
[FONT=&quot]list[first:last][/FONT][FONT=&quot]slice up the list into a sublist. Last is not included![/FONT]

Kod:
>>> words = ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> words[0:3] # beaware 3 is not included!
  ['Python', 'is', 'awesome']
  >>> words[:3] # is also same with [0:3]
  ['Python', 'is', 'awesome']
  Since we can use negative indexes, lets find the last 3 elements at the list, and try other variations.
  >>> words[-3:]
  [1, 2, 3]
  >>> words[-3:-1]
  [1, 2]
   >>> words[-3:0] # were you expecting something else ?
[FONT=&quot]
[/FONT]

[FONT=&quot]Extended Slicing[/FONT]
[FONT=&quot]list[first:last:step][/FONT][FONT=&quot]slice up a list with step[/FONT]

Kod:
>>> words = ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> words[::2]
  ['Python', 'awesome', 'is', 'nice', 2]
  >>> words[1:6:2]
   ['is', 'Go', 'also']


[FONT=&quot]Reverse & Copy a List[/FONT]
[FONT=&quot]list.reverse()[/FONT]

Kod:
>>> text = words
  >>> text
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> text.reverse()
  >>> text
  [3, 2, 1, 'nice', 'also', 'is', 'Go', 'awesome', 'is', 'Python']
  >>> words
  [3, 2, 1, 'nice', 'also', 'is', 'Go', 'awesome', 'is', 'Python']
  >>> words.copy()
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
   AttributeError: 'list' object has no attribute 'copy'


[FONT=&quot]As you see the original list modified when [/FONT][FONT=&quot]reverse[/FONT][FONT=&quot] method runs and since [/FONT][FONT=&quot]text=words[/FONT][FONT=&quot] both variables pointing to the same value. How can we get a shallow copy of the list ?[/FONT]

Kod:
>>> words.reverse()
  >>> words
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> text
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> text = list(words) # create a new copy of the list
  >>> text
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> words
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> id(text)
  4299649968
  >>> id(words)
  4299609872
  >>> text.reverse()
  >>> text
  [3, 2, 1, 'nice', 'also', 'is', 'Go', 'awesome', 'is', 'Python']
  >>> words
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> other_reverse_text = words[0:-1] # slicing creating a new list instance as well
  >>> other_reverse_text
  ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2]
  >>> id(other_reverse_text)
  4299649896
  >>> id(words)
   4299609872
[FONT=&quot]You can also use extended slicing to get the reversed copy of a list[/FONT]

Kod:
>>> words = ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
  >>> words[::-1]
   [3, 2, 1, 'nice', 'also', 'is', 'Go', 'awesome', 'is', 'Python']
[FONT=&quot]Oh I love Python![/FONT]

[FONT=&quot]For loop, iteration[/FONT]
[FONT=&quot]Iterating though each element within the list[/FONT][FONT=&quot]
[/FONT]

Kod:
words = ['Python', 'is', 'awesome']
  >>> for word in words:
  ...     print word
  Python
  is
   awesome


[FONT=&quot]Sort[/FONT]
[FONT=&quot]Builtin [/FONT][FONT=&quot]sorted()[/FONT][FONT=&quot] or[/FONT][FONT=&quot]list.sort()[/FONT][FONT=&quot] sorts the elements of a list.[/FONT]

Kod:
>>> for word in sorted(words):
  ...     print word
  !
  awesome
  is
   Python
[FONT=&quot]Be aware that [/FONT][FONT=&quot]list.sort()[/FONT][FONT=&quot] has a side effect that the actual list is sorted and the place of the elements will be changed afterwards
[/FONT]

Kod:
>>> words = ['Python','is','awesome','testing']
  >>> sorted(words)
  ['Python', 'awesome', 'is', 'testing']
  >>> words
  ['Python', 'is', 'awesome', 'testing']
  >>> words.sort()
  >>> words
   ['Python', 'awesome', 'is', 'testing']
 
Son düzenleme:
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.