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

python中元组与列表的区别,布布扣,bubuko.com

python中元组与列表的区别

上一篇:90分钟实现一门编程语言——极简解释器教程


下一篇:java笔试面试题---基础部分4