Cooperation and diversity abound in nature despite cooperators risking exploitation from defectors and superior competitors displacing weaker ones. Understanding the persistence of cooperation and diversity is therefore a major problem for evolutionary ecology, especially in the context of well-mixed populations, where the potential for exploitation and displacement is greatest. Here, we demonstrate that a 'loner effect', described by economic game theorists, can maintain cooperation and diversity in real-world biological settings. We use mathematical models of public-good-producing bacteria to show that the presence of a loner strain, which produces an independent but relatively inefficient good, can lead to rock-paper-scissor dynamics, whereby cooperators outcompete loners, defectors outcompete cooperators and loners outcompete defectors. These model predictions are supported by our observations of evolutionary dynamics in well-mixed experimental communities of the bacterium Pseudomonas aeruginosa. We find that the coexistence of cooperators and defectors that produce and exploit, respectively, the iron-scavenging siderophore pyoverdine, is stabilized by the presence of loners with an independent iron-uptake mechanism. Our results establish the loner effect as a simple and general driver of cooperation and diversity in environments that would otherwise favour defection and the erosion of diversity.