search

Day - List Functions

Jan 03, 2025 am 11:51 AM

Day - List Functions

extend() vs append() vs insert():

extend()-Adds all elements from an iterable (e.g., list, tuple) to the end of the list.
append()-Adds a single element to the end of the list.
insert()-Inserts a single element at a specified index in the list.

Example for extend():

l1 = [10,20,30]
l2 = [40,50,60]
l1.extend(l2)
print(l1)
print(len(l1))

[10, 20, 30, 40, 50, 60]
6

Example for append():

l1 = [10,20,30]
l2 = [40,50,60]
l1.append(l2)
print(l1)
print(len(l1))

[10, 20, 30, [40, 50, 60]]
4

append() vs extend():

l1 = [10,20,30]
l1.append('abcd')
print(l1)
l1.extend('pqrs')
print(l1)
[10, 20, 30, 'abcd']
[10, 20, 30, 'abcd', 'p', 'q', 'r', 's']

reverse():

The reverse() method in Python is used to reverse the order of the elements in a list in place.

l1 = [10,20,30]
l1.reverse()
print(l1)

[30, 20, 10]

sort():

The sort() method in Python is used to sort the elements of a list in place. It arranges the elements in ascending order by default.

l1 = [10,200,30]
l1.sort()
print(l1)

l1.sort(reverse=True)
print(l1)

[10, 30, 200]
[200, 30, 10]

sorted():

The sorted() function in Python is similar to the sort() method, but with key differences. It returns a new sorted list without modifying the original list.

my_list = [3, 1, 4, 5, 2]
sorted_list = sorted(my_list)
print(sorted_list) 
print(my_list) 
[1, 2, 3, 4, 5]
[3, 1, 4, 5, 2]

min(): To find minimum value in given input.
max(): To find maximum value in given input.
sum(): To find sum of all values in given input.

l1 = [10,200,30,40,50]
print(min(l1))
print(max(l1))
print(sum(l1))

10
200
330

inf(Infinity):

float('inf'):Used to find maximum number.
-float('inf'):Used to find minimum number.

1. Find second minimum value in given input.

l1 = [10,20,310,40,50]
min_value = float('inf')  
second_min = float('inf')  

i = 0
while i <len if l1 second_min="min_value" min_value="l1[i]" elif i else: print>





<pre class="brush:php;toolbar:false">20

2. Find second maximum value in given input.

l1 = [10,20,30,40,50]
max_value = -float('inf')  
second_max = -float('inf') 

i = 0
while i <len if l1>max_value: 
        second_max = max_value
        max_value = l1[i] 
    elif l1[i]>second_max:
        second_max = l1[i]
    i+=1
else:
    print(second_max)

</len>
40

Bubble sort:

It compares adjacent elements, and swaps them if they are in the wrong order.

Example:1

l1 = [40,30,20,10]
i = 0 
while i<len if l1>l1[i+1]:
        l1[i], l1[i+1] = l1[i+1], l1[i]
    i+=1
print(l1)
i = 0 
while i<len if l1>l1[i+1]:
        l1[i], l1[i+1] = l1[i+1], l1[i]
    i+=1
print(l1)

</len></len>
[30, 20, 10, 40]
[20, 10, 30, 40]

Example:2(using double sort change given list in ascending order and find Kth highest value in a given list)

l1 = [40,30,20,10]

#kth highest value in a given list
j = 1
while jl1[i+1]:
            l1[i], l1[i+1] = l1[i+1], l1[i]
        i+=1
    j+=1
print(l1)
print(l1[-3])
[10, 20, 30, 40]
20

in and not in operators:

Python’s in and not in operators allow you to quickly determine if a given value is or isn’t part of a collection of values.

l1 = [100,67,54,101,220, 670,45, 32]
print(100 in l1)
print(100 not in l1)
print(120 in l1)
print(120 not in l1)
True
False
False
True

Reversing a string:

s = "today is thursday"
reverse = ""
i = 0

while i<len reverse="reverse" s i print>





<pre class="brush:php;toolbar:false">yadsruht si yadot

The above is the detailed content of Day - List Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools