3.1.4.12 Lists - collections of data | lists and loops
Lists in action
Now you can easily swap the list's elements to reverse their order:
myList = [10, 1, 8, 3, 5]
myList[0], myList[4] = myList[4], myList[0]
myList[1], myList[3] = myList[3], myList[1]
print(myList)
Run the snippet. Its output should look like this:
[5, 3, 8, 1, 10]
It looks fine with five elements.
Will it still be acceptable with a list containing 100 elements? No, it won't.
Can you use the
for
loop to do the same thing automatically, irrespective of the list's length? Yes, you can.
This is how we've done it:
myList = [10, 1, 8, 3, 5]
length = len(myList)
for i in range(length // 2):
myList[i], myList[length - i - 1] = myList[length - i - 1], myList[i]
print(myList)
Note:
- we've assigned the
length
variable with the current list's length (this makes our code a bit clearer and shorter) - we've launched the
for
loop to run through its bodylength // 2
times (this works well for lists with both even and odd lengths, because when the list contains an odd number of elements, the middle one remains untouched) - we've swapped the ith element (from the beginning of the list) with the one with an index equal to
(length - i - 1)
(from the end of the list); in our example, fori
equal to0
the(l - i - 1)
gives4
; fori
equal to1
, it gives3
- this is exactly what we needed.
Lists are extremely useful, and you'll encounter them very often.
The Casino Review and Rating - Mr.CD
ReplyDeleteRead our 서울특별 출장샵 review of the 동두천 출장안마 Mr.Casino.com casino 시흥 출장샵 to find out how you can 평택 출장샵 claim a €1500 bonus to play MrCasino has been 구미 출장안마 operating for the past year as part of Rating: 5 · Review by Dr