using reverse in list of tuples

J

james_027

hi,

I am trying to reverse the order of my list of tuples and its is
returning a None to me. Is the reverse() function not allow on list
containing tuples?

Thanks,
James
 
R

rantingrick

I am trying to reverse the order of my list of tuples and its is
returning a None to me. Is the reverse() function not allow on list
containing tuples?


list.revese() is an in-place operation! don't try to assign the return
value back to your list!
lst = [(x, x+1) for x in range(5)]
lst [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
lst.reverse()
lst
[(4, 5), (3, 4), (2, 3), (1, 2), (0, 1)]
 
T

Terry Reedy

hi,

I am trying to reverse the order of my list of tuples and its is
returning a None to me. Is the reverse() function not allow on list
containing tuples?

No. Mutation methods of builtins generally return None.
 
M

Marco Nawijn

hi,

I am trying to reverse the order of my list of tuples and its is
returning a None to me. Is the reverse() function not allow on list
containing tuples?

Thanks,
James

As the others already mentioned list.reverse() is in-place, just as
for
example list.sort(). Alternatively, use the builtin reversed() or
sorted()
functions to get a return value (they will leave the original list
unmodified.

Example: ...print item
This will produce:
2
1
0

Note that reversed returns an iterator.

Marco
 
S

Steven W. Orr

As the others already mentioned list.reverse() is in-place, just as
for
example list.sort(). Alternatively, use the builtin reversed() or
sorted()
functions to get a return value (they will leave the original list
unmodified.

Example:
...print item
This will produce:
2
1
0

Note that reversed returns an iterator.

Marco

How about just doing it the old fashioned way via slicing.
foo = (4,5,8,2,9,1,6)
foo[::-1] (6, 1, 9, 2, 8, 5, 4)

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.10 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org/

iEYEARECAAYFAkwRCgwACgkQRIVy4fC+NyTCswCdFI3RV1m6eTEvfMo314Dklc6U
9rkAn1j+zYNzNR4gB5WWajVns6B+P74o
=ALG4
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top