python中元组与列表的区别
python中使用元组与列表的主要区别在于,元组创建后不可修改,列表在任何时刻都可以修改。
元组举例:
breakfast = ("bread,milk,tea") print(breakfast) 输出:bread,milk,tea
注意,元组中的元素用()括起来,使用时:breakfast[0] <=>"bread"
列表举例:
sports = ["pingpong","basketball","football"] print(sports) 输出:[‘pingpong‘, ‘basketball‘, ‘football‘]
注意,列表中使用[]将列表中的元素括起来,使用时:sports[0] <=> "pingpong"
往列表中添加单个元素:
sports.append("run")
往列表中添加多个元素或元组
sports = ["pingpong","basketball","football"] breakfast = ("bread","milk","tea") print(sports) sports.extend(breakfast) print(sports) sports.extend(["1","2","3"]) //此处需用[] print(sports) 输出: [‘pingpong‘, ‘basketball‘, ‘football‘] [‘pingpong‘, ‘basketball‘, ‘football‘, ‘bread‘, ‘milk‘, ‘tea‘] [‘pingpong‘, ‘basketball‘, ‘football‘, ‘bread‘, ‘milk‘, ‘tea‘, ‘1‘, ‘2‘, ‘3‘]
相同之处,元组和数据不可以越界访问。
本文出自 “果子” 博客,请务必保留此出处http://chenqin.blog.51cto.com/2356777/1381863
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。