Reputation: 25
I have variables of tuples:
student1 = ("Allan", "Anderson")
student2 = ("Barry", "Byars")
brendan = ("Brendan","Smith")
sandy = ("Sandy","Garner")
I want to put them in a list:
students = [("Allan", "Anderson"),("Barry", "Byars")]
How would you do this? I have 7 variables of tuples and is there an efficient way to do this?
I know students.append() can do it but because I have 7 variables, is there a faster way?
Upvotes: 1
Views: 261
Reputation: 3932
You should use a better data structure here (like a dictionary) :
Students = {
"student1": ("Allan", "Anderson"),
"student2": ("Barry", "Byars"),
"brendan": ("Brendan", "Smith"),
"sandy": ("Sandy", "Garner")
}
StudentList = [student for student in Students.values()]
print(StudentList)
Output
[('Allan', 'Anderson'), ('Barry', 'Byars'), ('Brendan', 'Smith'), ('Sandy', 'Garner')]
In this way, if you want to add another list you just have to add a single line in your dictionary without changing any logic :
Students["JohnDoe"] = ("John", "Doe")
Output :
[('Allan', 'Anderson'), ('Barry', 'Byars'), ('Brendan', 'Smith'), ('Sandy', 'Garner'), ('John', 'Doe')]
Upvotes: 8
Reputation: 362
The simple way to achieve this can be,
student1 = ("Allan", "Anderson")
student2 = ("Barry", "Byars")
student = [student1, student2]
print(student)
Upvotes: -1
Reputation: 9494
You can define your variables as a dictionary where the keys are the names of the variables.
For example:
vars_dict = {
"student1": ("Allan", "Anderson"),
"student2": ("Barry", "Byars")
}
and then using dict's values()
method get all values as a list:
students = list(vars_dict.values())
Upvotes: 0
Reputation: 1808
If there's no structure to your variable names, this is the easiest way.
students = [student1, student2, brendan, sandy]
[('Allan', 'Anderson'), ('Barry', 'Byars'), ('Brendan', 'Smith'), ('Sandy', 'Garner')]
Upvotes: 4