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.
Everything starts with the square brackets []
Lets start with a basic example. Let's say we have a sentence.
>>> words = ['Python','is','awesome']or list(iterable) which can also convert other types of iterable objects(sequences) into a list
>>> 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]list.append() 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.
>>> words.append("!")
>>> words
['Python','is','awesome','!']Lets find out how many elements do we have in our list.. Python builtin functionlen() helps us as always
>>> len(words)
4list.insert(location, element) inserts the elemented into the given location. If the location is larger than the number of elements, inserts the element to the last position.
>>> 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']Deletes the last element from the list and returns it.
>>> words = ['Python','is','awesome','hosting']
>>> words.pop() # remove the added hosting, pop used
'hosting'
>>> words
['Python','is','awesome']Builtin del command helps to remove an element
>>> 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']You can use + 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.
>>> 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
['Python', 'is', 'awesome', '.', 'Go', 'is', 'also', 'nice']list.extend(sequence) adds the given sequence ( list is also a sequence ) to the actual list. The return of the call is None
>>> 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
['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]Be careful
>>> 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()Nothing is printed, because our list became a None (Object). words[len(words)-1] 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?!
>>> words[-1]
'awesome'
>>> words[-2]
'is'
>>> words[-3]
'Python'list[first:last] slice up the list into a sublist. Last is not included!
>>> 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 ? :)
[]list[first:last:step] slice up a list with step
>>> 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']list.reverse()
>>> 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'As you see the original list modified when reverse method runs and since text=words both variables pointing to the same value. How can we get a shallow copy of the list ?
>>> 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)
4299609872You can also use extended slicing to get the reversed copy of a list
>>> words = ['Python', 'is', 'awesome', 'Go', 'is', 'also', 'nice', 1, 2, 3]
>>> words[::-1]
[3, 2, 1, 'nice', 'also', 'is', 'Go', 'awesome', 'is', 'Python']Oh I Python!
Iterating though each element within the list
words = ['Python', 'is', 'awesome']
>>> for word in words:
... print word
Python
is
awesomeBuiltin sorted() or list.sort() sorts the elements of a list.
>>> for word in sorted(words):
... print word
!
awesome
is
Python Be aware that list.sort() has a side effect that the
actual list is sorted and the place of the elements will be changed afterwards
>>> words = ['Python','is','awesome','testing']
>>> sorted(words)
['Python', 'awesome', 'is', 'testing']
>>> words
['Python', 'is', 'awesome', 'testing']
>>> words.sort()
>>> words
['Python', 'awesome', 'is', 'testing']