6

I have two lists:

country_name = ['South Africa', 'India', 'United States']
country_code = ['ZA', 'IN', 'US']

I want to group the country name and its corresponding code together and then perform a sort operation to do some processing

When I tried to zip these 2 lists, I am getting the 1st character from both the lists as the output.

I also tried doing this:

for i in xrange(0,len(country_code):
     zipped = zip(country_name[i][:],country_code[i][:])
     ccode.append(zipped)

to zip the entire string, but it didn't work. Also I am not sure that after zipping the 2 list, I will be able to sort the resulting list or not.

martineau
  • 119,623
  • 25
  • 170
  • 301
Anurag Sharma
  • 4,839
  • 13
  • 59
  • 101

2 Answers2

7

You are using zip() wrong; use it with the two lists:

zipped = zip(country_name, country_code)

You are applying it to each country name and country code individually:

>>> zip('South Africa', 'ZA')
[('S', 'Z'), ('o', 'A')]

zip() combines the two input sequences by pairing off each element; in strings, the individual characters are the elements of the sequence. Because there are only two characters in the country codes, you end up with lists of two elements, each a tuple of paired characters.

Once you combined both lists into a new one, you can most certainly sort that list, either on the first or second element:

>>> zip(country_name, country_code)
[('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US')]
>>> sorted(zip(country_name, country_code))
[('India', 'IN'), ('South Africa', 'ZA'), ('United States', 'US')]
>>> from operator import itemgetter
>>> sorted(zip(country_name, country_code), key=itemgetter(1))
[('India', 'IN'), ('United States', 'US'), ('South Africa', 'ZA')]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5

answer is in your question - use zip:

>>> country_name = ['South Africa', 'India', 'United States']
>>> country_code = ['ZA', 'IN', 'US']
>>> zip(country_name, country_code)
[('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US')]

If you have lists with different lengths, you could use itertools.izip_longest:

>>> from itertools import izip_longest
>>> country_name = ['South Africa', 'India', 'United States', 'Netherlands']
>>> country_code = ['ZA', 'IN', 'US']
>>> list(izip_longest(country_name, country_code))
[('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US'), ('Netherlands', None)]
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197