Python | list,tuple相关

Common sequence operations

  1. len(sequence) Returns the length of the sequence
  2. for element in sequence Iterates over each element in the sequence
  3. if element in sequence Checks whether the element is part of the sequence
  4. sequence[i] Accesses the element at index i of the sequence, starting at zero
  5. sequence[i:j] Accesses a slice starting at index i, ending at index j-1. If i is omitted, it’s 0 by default. If j is omitted, it’s len(sequence) by default.
  6. for index, element in enumerate(sequence) Iterates over both the indexes and the elements in the sequence at the same time

Check out the official documentation for sequence operations.

List-specific operations and methods

  1. list[i] = x Replaces the element at index i with x
  2. list.append(x) Inserts x at the end of the list
  3. list.insert(i, x) Inserts x at index i
  4. list.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.
  5. list.remove(x) Removes the first occurrence of x in the list
  6. list.sort() Sorts the items in the list
  7. list.reverse() Reverses the order of items of the list
  8. list.clear() Removes all the items of the list
  9. list.copy() Creates a copy of the list
  10. list.extend(other_list) Appends all the elements of other_list at the end of list

Most of these methods come from the fact that lists are mutable sequences. For more info, see the official documentation for mutable sequences and the list specific documentation.

List comprehension

  1. [expression for variable in sequence] Creates a new list based on the given sequence. Each element is the result of the given expression.
  2. [expression for variable in sequence if condition] Creates a new list based on the given sequence. Each element is the result of the given expression; elements only get added if the condition is true.

Source: Coursera

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Crypto投资小白书

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值