您的位置:首页 > 编程语言 > Python开发

python basics - Datatypes Collections and Lists

2012-10-25 00:00 253 查看
This is one of few coming series that serves as a memo of the common basic syntax when you manipulate python and focus on the basic syntax and built-in data types.

In this post, List will be discussed, including how to define a list and how to manipulate the list and how to convert list and tuples, the major difference between list and tuple is immutability.

in the following code , the following will be displayed.

create a list of empty elements, one element, elements of the same type, elements of mixed types

concat, reverse a list, remove an element from a list

'''
Created on 2012-10-22

@author: Administrator

file: Lists.py
description: this file is to test the use of the list - one of the built-in collection types s
'''

def demoLists():
empty_list = []
one_elem_list = [1]
isovalent_list = [1, 2,3,4,5,6,7, 8, 9, 12]
unisovalent_list = [1, "two", 3, 4.0, ["a", "b"], (5,6)] # 3L is no longer supported by python 3.x
print("*** empty list ")
print(empty_list)
print("*** one element list ")
print(one_elem_list)
print("*** isovalent list ")
print (isovalent_list)
print("***unisovalent list")
print(unisovalent_list)

def list_operation():
x = [1, 2,3, 4, 5, 6, 7, 8, 9]
print("*** original list:")
print(x)
print("*** len(x): ")
print(len(x))
y = [-1, 0] + x
print("** print the concatenated list:")
print(y)
print("**reversed list")
x.reverse() # you cannot do x = x.reverse(), otherwise, undefined behavior will happen
print(x)
x.remove(1)
print(x)
# another way of delete one element
del x[1]
print(x)

if __name__ == '__main__':
demoLists()
list_operation()


the following code shows how to convert from list to tuple and vice versa.

convert from List to tuple and the other way around.

'''
Created on 2012-10-22

@author: Administrator
file: ListTupleOps.py
description: this file demonstrate the conversion between list and tuples
'''
def convert_and_back():
x = [1, 2, 3, 4]
y = tuple(x)
print ("*** list x:")
print(x)
print ("*** tuple x:")
print(y)
x = list(y)

if __name__ == '__main__':
convert_and_back()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python