OnJava8-Examples/arrays/PythonLists.py

37 lines
1.0 KiB
Python
Raw Normal View History

2015-09-07 11:44:36 -06:00
# arrays/PythonLists.py
# (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
# We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
# Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
aList = [1, 2, 3, 4, 5]
print(type(aList)) # <type 'list'>
print(aList) # [1, 2, 3, 4, 5]
print(aList[4]) # 5 Basic list indexing
aList.append(6) # lists can be resized
aList += [7, 8] # Add a list to a list
print(aList) # [1, 2, 3, 4, 5, 6, 7, 8]
aSlice = aList[2:4]
print(aSlice) # [3, 4]
class MyList(list): # Inherit from list
# Define a method; 'this' pointer is explicit:
2015-06-15 17:47:35 -07:00
def getReversed(self):
reversed = self[:] # Copy list using slices
reversed.reverse() # Built-in list method
return reversed
# No 'new' necessary for object creation: {#24-no-new-necessary-for-object-creation}
2015-06-15 17:47:35 -07:00
list2 = MyList(aList)
print(type(list2)) # <class '__main__.MyList'>
print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1]
2016-01-25 18:05:55 -08:00
output = """
<class 'list'>
[1, 2, 3, 4, 5]
5
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4]
<class '__main__.MyList'>
[8, 7, 6, 5, 4, 3, 2, 1]
"""