Trey Hunner 🐍 on Nostr: Need to copy an iterable in #Python? I usually recommend using the list constructor. ...
Need to copy an iterable in #Python? I usually recommend using the list constructor.
old = [2, 1]
new = list(old)
If you're CERTAIN you have a list, you could use copy:
new = old.copy()
I don't recommend slicing because it's hard to read 😐:
new = old[:]
The [*...] syntax works, but I find it less explicit than list(...):
new = [*old]
If you're accepting ANY iterable (duck typing! 🦆), I'd copy using list(...).
More on when I prefer list(...) and when I don't: pym.dev/using-list
Published at
2024-08-05 16:35:08Event JSON
{
"id": "aa973c0a85c49ae1102a1987821f4c3df04173dd6061ee786b6a12a21bbe11a5",
"pubkey": "7e9159fbfd5526415c8d2de2e4c7654e3660883f9ccae720a70fa3c1f3cf1f45",
"created_at": 1722875708,
"kind": 1,
"tags": [
[
"proxy",
"https://mastodon.social/@treyhunner/112910382402588800",
"web"
],
[
"t",
"python"
],
[
"proxy",
"https://mastodon.social/users/treyhunner/statuses/112910382402588800",
"activitypub"
],
[
"L",
"pink.momostr"
],
[
"l",
"pink.momostr.activitypub:https://mastodon.social/users/treyhunner/statuses/112910382402588800",
"pink.momostr"
],
[
"-"
]
],
"content": "Need to copy an iterable in #Python? I usually recommend using the list constructor.\n\nold = [2, 1]\nnew = list(old)\n\nIf you're CERTAIN you have a list, you could use copy:\n\nnew = old.copy()\n\nI don't recommend slicing because it's hard to read 😐:\n\nnew = old[:]\n\nThe [*...] syntax works, but I find it less explicit than list(...):\n\nnew = [*old]\n\nIf you're accepting ANY iterable (duck typing! 🦆), I'd copy using list(...).\n\nMore on when I prefer list(...) and when I don't: pym.dev/using-list",
"sig": "b59c610538fad1eee722b1151778c3d788f8d8e68ec09829ed3cda46d8caf0feedf052d8f68a47920845aa7a65df9030cfe6523aeac12f77ce85a20e2a7cf970"
}