python基础——第四天(list和tuple)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZENGZISUZI/article/details/81195283

list

是一种有序的集合,可以随时添加和删除其中的元素的内置数据列表。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#2018年7月25日
#by youyi
#list定义
friends = ['旺财','二狗','右一']
print(friends)
#list可以用len()函数获取list元素个数
print(len(friends))
#和其他语言一样可以用索引访问list中的每一个位置的元素
print(friends[0],'和',friends[1],'和',friends[2],'是好朋友!')
#负数索引可以用来倒数着访问
print('list 最后一个元素是:',friends[-1])
print('list 倒数第二个元素是:',friends[-2])
#在list末尾追加元素
friends.append('二百五')
print(friends)
#删除list末尾元素
friends.pop()
print(friends)
#追加元素到指定位置
friends.insert(1,'250')
print(friends)
#删除指定位置的元素
friends.pop(2)
print(friends)
#替换自定位置的元素
friends[2] = '单身狗'
print(friends)

这里写图片描述
另外,list里的元素可以是不同数据类型,也可以是另一个list。如果list中没有元素,则长度为0.
这里写图片描述

tuple

有序列表,一旦初始化就不能修改。和list一样可以通过下标访问元素。但是当我们定义一个tuple的时候,元素个数必须指定。
注意:

  1. 当需要定义一个只有一个元素的tuple时,需要在1后加上“,”区别数学上的计算的小括号。
  2. tuple虽然是定义了,元素就不可变,但是如果tuple里的元素有可变的list,这样通过改变这个list,元素指向list这是不变的,但是实际上内容可以通过list改变。
    这里写图片描述

猜你喜欢

转载自blog.csdn.net/ZENGZISUZI/article/details/81195283
今日推荐