I'm seeing a slight difference:
"The students did the homework themselves." = without outside help.
"The students did the homework by themselves." = also "without outside help", but "by themselves" can also mean "alone". The first example hints that the students could have worked together, however the second example hints that the students each worked separately.
It's a really tiny issue, but generally you can use either one. :)