python中列表和元組的基本操作

來源:互聯網
上載者:User

標籤:類型   tuple   變化   整型   基本   print   例子   https   types   

列表的基本操作,例子中使用的python3,python2中用print list
# 1. 定義一個含有5個數位列表list1 = [5, 6, 7, 8, 9]# 使用type( )可以查看變數的類型print(type(list1))# 2. 為列表增加一個元素 100# 列表內建的方法很豐富,參考官方文檔# https://docs.python.org/3.5/library/stdtypes.html#sequence-types-list-tuple-rangelist1.append(100)print(list1)# 3. 使用remove()刪除一個元素後觀察列表的變化list1.remove(7)print(list1)# 4. 使用切片操作分別取出列表的前三個元素,取出列表的最後一個元素print(list1[0:3])# 注意取出最後一個元素的類型為整型print(list1[-1])

元組的基本操作
# 1. 定義一個任意元組,對元組使用append() 查看錯誤資訊tuple1 = (‘x‘, ‘y‘, 3, 4, 5)# 元組定義完成一般不可變,也沒有append方法,會報錯# AttributeError: ‘tuple‘ object has no attribute ‘append‘# tuple1.append()# 2. 訪問元組中的倒數第二個元素# 元組也是序列,因此可以使用序列操作print(tuple1[-2])# 3. 定義一個新的元組,和 1. 的元組串連成一個新的元組tuple2 = (‘a‘, ‘b‘, ‘c‘)print(tuple1 + tuple2)# 組成新的元組之後會新申請一塊記憶體存放元組,操作的兩個元組不變print(tuple1)print(tuple2)# 4. 計算元組元素個數# 可以使用len( )方法計算,也可以使用內建的__len__( )方法得到元組元素的個數,# 元組元素的個數和總長度是一樣的print(len(tuple1))print(tuple1.__len__())
 

python中列表和元組的基本操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.