-1
names = ['vik', 'zed', 'loren', 'tal', 'yam', 'jay', 'alex', 'gad', 'dan', 'hed']
cities = ['NY', 'NY', 'SA', 'TNY', 'LA', 'SA', 'SA', 'NY', 'SA', 'LA']
ages = ['28', '26', '26', '31', '28', '23', '29', '31', '27', '41']

How do I create a new list with names of all the people from SA?

I tried getting all 'SA' positions and then print the same positions that are in the names list,

pos = [i for i in range(len(names)) if cities[i] == 'SA']
print(names[pos]) 

Returns the following error:

TypeError: list indices must be integers or slices, not list

I've also attempted to loop over the positions in cities and then do pretty much the same but one by one, but i still wasn't able to put in a list

pos = [i for i in range(len(names)) if cities[i] == 'SA']
x = 1
for i in pos:
     x+=1
Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
AlfaGoose
  • 1
  • 3

3 Answers3

2

You can zip the names ages and cities together then use a list comprehension to filter those by city

 [(a,b,c) for a,b,c in zip(names, cities, ages) if b == "SA"]

returns

[('loren', 'SA', '26'), ('jay', 'SA', '23'), ('alex', 'SA', '29'), ('dan', 'SA', '27')]
Sayse
  • 42,633
  • 14
  • 77
  • 146
1

Enumerate the list of cities so you get their index as well, and collect the names if the city matches:

names = ['vik', 'zed', 'loren', 'tal', 'yam', 'jay', 'alex', 'gad', 'dan', 'hed']
cities = ['NY', 'NY', 'SA', 'TNY', 'LA', 'SA', 'SA', 'NY', 'SA', 'LA'] 
  
print( [names[idx] for idx,c in enumerate(cities) if c == "SA"] ) 

Output:

['loren', 'jay', 'alex', 'dan']

See: enumerate on python.org

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

How do i create a new list with names of all the people from SA?

Oneliner (but maybe the question is unclear) using zip and list comprehension with a filter

lst = [n for n, c in zip(names, cities) if c == 'SA']
print(lst)

Ouput:

['loren', 'jay', 'alex', 'dan']

Explaination

The oneliner is equivalent to:

lst = []
for name, city in zip(names, cities):
    if city == 'SA':
        lst.append(name)
print(lst)

zip iterates over the names and cities lists in parallel, producing tuples in the form "(<a_name>, <a_city>)"

hpchavaz
  • 1,368
  • 10
  • 16