The primary habitat of Escherichia coli is the vertebrate gut, where it is the predominant aerobic organism, living in symbiosis with its host. Despite the occurrence of recombination events, the population structure is predominantly clonal, allowing the delineation of major phylogenetic groups. The genetic structure of commensal E. coli is shaped by multiple host and environmental factors, and the determinants involved in the virulence of the bacteria may in fact reflect adaptation to commensal habitats. A better characterization of the commensal niche is necessary to understand how a useful commensal can become a harmful pathogen. In this Review we describe the population structure of commensal E. coli, the factors involved in the spread of different strains, how the bacteria can adapt to different niches and how a commensal lifestyle can evolve into a pathogenic one.