Former President Barack Obama delivered a forceful rejection of identity politics during a speech Tuesday, saying democracy doesn't work if people dismiss opposing voices for reasons like they're "white" or "male."

Speaking at the Nelson Mandela Annual Lecture in South Africa, Obama said to make democracy work that people had to follow the example of Mandela in engaging with people who look and think differently.

"This is hard," Obama said.

"Most of us prefer to surround ourselves with opinions that validate what we already believe," he added. "You notice, the people who you think are smart are the people who agree with you. Funny how that works."

Obama said perhaps one's mind could be changed by talking to someone who thinks differently.

"You can't do this if you just out-of-hand disregard what your opponents have to say from the start," he said. "You can't do it if you insist that those who aren't like you because they're white or because they're male, that somehow there's no way they can understand what I'm feeling, that somehow they lack standing to speak on certain matters."

Obama, referring to him by his Xhosa clan name "Madiba," recounted Mandela's study of white Afrikaans while serving 27 years in prison. He was elected president in 1994, four years after his release and shortly after he helped South Africa end its policy of racial separation and discrimination known as apartheid.

"When he got out of prison, he extended a hand to those who had jailed him, because he knew that they had to be a part of the democratic South Africa that he wanted to build," Obama said.

New York Times columnist Bari Weiss called Obama's remarks "an amazing rebuke to the dead-end of identity politics."

An amazing rebuke to the dead-end of identity politics. https://t.co/9hq9BXd6XC — Bari Weiss (@bariweiss) July 17, 2018

Obama made similar comments while president, once saying in 2015 that liberals on college campuses were often too close-minded and didn't want to engage with conservatives.

"I’ve heard some college campuses where they don’t want to have a guest speaker who is too conservative or they don’t want to read a book if it has language that is offensive to African Americans or somehow sends a demeaning signal towards women," he said. "And you know, I've got to tell you, I don’t agree with that either. I don’t agree that you, when you become students at colleges, have to be coddled and protected from different points of view."

"You know, I think you should be able to—anybody who comes to speak to you and you disagree with, you should have an argument with them. But you shouldn’t silence them by saying, ‘You can’t come because I'm too sensitive to hear what you have to say.’ That’s not the way we learn either."