Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Swap the First and Last Elements of a List

Python Swap the First and Last Elements of a List

Document Object Reference Manual Python3 Examples

Define a list and swap the first and last elements of the list.

For example:

对调前 : [1, 2, 3]
对调后 : [3, 2, 1]

Example 1

def

swapList

(

newList

)

:

    size

=

len

(

newList

)

     

    temp

=

newList

[

0

]

    newList

[

0

]

=

newList

[

size -

1

]

    newList

[

size -

1

]

=

temp

     

   

return

newList

newList

=

[

1

,

2

,

3

]

 

print

(

swapList

(

newList

)

)

The output of the above example is:


[3, 2, 1]

Example 2

def

swapList

(

newList

)

:

     

    newList

[

0

]

,

newList

[

1

]

=

newList

[

1

]

,

newList

[

0

]

 

   

return

newList

     

newList

=

[

1

,

2

,

3

]

print

(

swapList

(

newList

)

)

The output of the above example is:


[3, 2, 1]

Example 3

def

swapList

(

list

)

:

     

    get

=

list

[

1

]

,

list

[

0

]

     

   

list

[

0

]

,

list

[

1

]

=

get

     

   

return

list

     

newList

=

[

1

,

2

,

3

]

print

(

swapList

(

newList

)

)

The output of the above example is:


[3, 2, 1]

Document Object Reference Manual Python3 Examples