Posts: 4,654
Threads: 1,497
Joined: Sep 2016
Feb-14-2020, 11:50 PM
(This post was last modified: Feb-17-2020, 08:41 AM by buran.)
why should i want to create a tuple instead of a list? or a frozenset instead of a set? or a namedtuple instead of a dictionary? are they more efficient? are they faster? do they use less memory? are they considered more pythonic for some reason?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 1,838
Threads: 2
Joined: Apr 2017
Feb-15-2020, 10:31 AM
(This post was last modified: Feb-15-2020, 12:03 PM by ndc85430.)
Immutability is, in general, a good idea. Some of the reasons why are explained here. OK, the examples are in PHP but the ideas are the same. I work daily in Scala (and sometimes other languages) where immutability is the default and can't say I miss mutability!
Posts: 4,654
Threads: 1,497
Joined: Sep 2016
Feb-16-2020, 08:15 AM
(This post was last modified: Feb-16-2020, 08:24 AM by Skaperen.)
then it should be allowed to morph a mutable object into its immutable form, in place, without the transient memory expansion of creating a new copy.
just don't change the mutable object. make your code do what it would do if the object is immutable. you can make a new copy of a mutable object, too.
so what about simple cases where i have lots of large lists i don't change, like after reading in a file. is there a reason to use tuples instead pf lists?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 8,168
Threads: 160
Joined: Sep 2016
Feb-16-2020, 10:49 AM
(This post was last modified: Feb-16-2020, 10:50 AM by buran.)
when reading from file, it may make sense to unpack each line into named tuple. It makes the code more readable after that. Of course assuming there is no more complicated custom class, instead of using named tuple.
Posts: 4,654
Threads: 1,497
Joined: Sep 2016
how is the code more readable? if it is that the way of coding around a tuple is easier to read, then just do the same way around a list.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 8,168
Threads: 160
Joined: Sep 2016
I said namedtuple, not tuple. For example
population.csv
Output: name,state,population
New York City,NY,8601186
Los Angeles,CA,4057841
Chicago,IL,2679044
Houston,TX,2359480
Phoenix,AZ,1711356
Philadelphia,PA,1576596
San Antonio,TX,1565929
San Diego,CA,1453775
Compare 4 snippets
import csv
from collections import namedtuple
with open('population.csv') as f:
next(f) # skip header
for line in f:
line = line.strip().split(',')
print(f'Population of {line[0]}, {line[1]} is {line[2]}')
with open('population.csv', newline='') as f:
rdr = csv.reader(f)
next(rdr) # skip header
for line in rdr:
print(f'Population of {line[0]}, {line[1]} is {line[2]}')
with open('population.csv', newline='') as f:
rdr = csv.DictReader(f)
for city in rdr:
print(f"Population of {city['name']}, {city['state']} is {city['population']}")
City = namedtuple('City', 'name state population')
with open('population.csv', newline='') as f:
rdr = csv.DictReader(f)
for record in rdr:
city = City(**record)
print(f"Population of {city.name}, {city.state} is {city.population}") This is very basic example (assuming no suitable custom class to use), but you get the idea. Imagine, you are not just printing elements.
In the last two snippets, if you just print city, the namedtuple is more readble than dhe dict
Output: OrderedDict([('name', 'Los Angeles'), ('state', 'CA'), ('population', '4057841')])
vs
Output: City(name='New York City', state='NY', population='8601186')
There is discussion about enhancement to csv module, to have a reader that returns nameduples, not dicts.
https://bugs.python.org/issue1818
But not sure what the current state is
Also instead of returning list/tuple from function, it is better to return namedtuple instead
Overall, using namedtuple instead of just tuple/list makes the element access and code readability better
Posts: 2,128
Threads: 11
Joined: May 2017
Feb-17-2020, 09:47 AM
(This post was last modified: Feb-17-2020, 09:47 AM by DeaD_EyE.)
Funny thing, today I used namedtuples from header.
You can use starmap from itertools.
import csv
from collections import namedtuple
from pathlib import Path
from itertools import starmap
def read_nt(csv_file):
with csv_file.open() as fd:
reader = csv.reader(fd, delimiter=",")
header = namedtuple("Header", next(reader))
for row in starmap(header, reader):
yield row
# you have to change the path
csv_file = Path.home() / "Desktop/akku.csv"
for row in read_nt(csv_file):
print(row) Output: Header(id='3093', cycle='86', row='1420', timestamp='2020-02-16 18:25:41.464264', voltage='13.0219659805298', current='-0.422915548086166', charge='79.4553909301758', cell_voltages='[3.2786877155303955, 3.2688629627227783, 3.232583522796631, 3.2427730560302734]', temperature='20.9888801574707')
Header(id='3094', cycle='86', row='1421', timestamp='2020-02-16 18:26:41.912095', voltage='13.0219659805298', current='-0.420677900314331', charge='79.4553909301758', cell_voltages='[3.2786877155303955, 3.2688629627227783, 3.232583522796631, 3.2427730560302734]', temperature='20.9888801574707')
Header(id='3095', cycle='86', row='1422', timestamp='2020-02-16 18:27:42.373194', voltage='13.0210456848145', current='-0.420677900314331', charge='79.4029693603516', cell_voltages='[3.2786877155303955, 3.2679216861724854, 3.232583522796631, 3.2418527603149414]', temperature='20.9888801574707')
It would be nice, to have this inside the csv-module.
Posts: 8,168
Threads: 160
Joined: Sep 2016
Feb-17-2020, 09:56 AM
(This post was last modified: Feb-17-2020, 09:56 AM by buran.)
even better than my example :-)
Posts: 4,654
Threads: 1,497
Joined: Sep 2016
so what's the advantage of a namedtuple over a namedlist ... err ... i mean, over a dictionary?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 2,128
Threads: 11
Joined: May 2017
Consumer which receives namedtuples:
csv_file = Path.home() / "Desktop/akku.csv"
for row in read_nt(csv_file):
print("Row ID:", row.row)
print("Voltage:", row.voltage)
print("Current:", row.current)
print("Charge:", row.charge)
print("Temp °C:", row.temperature) Consumer, which receives dicts:
csv_file = Path.home() / "Desktop/akku.csv"
for row in read_nt(csv_file):
print("Row ID:", row["row"])
print("Voltage:", row["voltage"])
print("Current:", row["current"])
print("Charge:", row["charge"])
print("Temp °C:", row["temperature"]) The namedtuple allows you attribute-access, the dict not.
|