【py code everyday line one】2023-03-01

Organizing a List

Python provides a number of different ways to organize your lists, depending on the situation.

Sorting a List Permanently with the sort() Method

change the order of the list to store them alphabetically

cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']

The sort() method changes the order of the list permanently
You can also sort this list in reverse-alphabetical order by passing the
argument reverse=True to the sort() method

cars = ['bmw','audi','toyota','subaru']
cars.sort(reverse= True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']

To maintain the original order of a list but present it in a sorted order, you
can use the sorted() function

cars = ['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

To reverse the original order of a list, you can use the reverse() method

cars = ['bmw','audi','toyota','subaru']
print(cars)

cars.reverse()
print(cars)

it simply reverses the order of the list.

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

Finding the Length of a List

You can quickly find the length of a list by using the len() function

cars = ['bmw','audi','toyota','subaru']
print(len(cars))
4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值