0

I have this

list = ['John', 21, 'Smith', 30, 'James', 25]

and I want to split them into the following

name = ['John', 'Smith', 'James']
age = [21, 30, 25]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 2
    [split list into 2 lists corresponding to every other element](//stackoverflow.com/q/23130300) – 001 Jan 23 '20 at 18:17
  • Hello Emmanuel, welcome to StackOverflow. This question is very basic, you should be able to find lots of answers by using your preferred search engine. It's also not entirely clear whether your input array has always the same pattern (alternating strings and ints) or if you have to parse the elements and check types. Please check out https://stackoverflow.com/questions/how-to-ask . – unixb0y Jan 23 '20 at 18:51

3 Answers3

2

You can do this. Don't use keywords and built-in names as variable names.

Using Slicing

Understanding Slicing Notation

lst=['John', 21, 'Smith', 30, 'James', 25]
name=lst[::2] 
age=lst[1::2]

Or you can use List Comprehension

List Comprehension Reference

name=[val for idx,val in enumerate(lst) if idx%2==0]
age=[val for idx,val in enumerate(lst) if idx%2==1]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
1

Iterate over the list. Append an element to the list name if the index of the element can be divided by two without remainder. If there is a remainder when dividing the index by two append the element to the list age. List indexes start at 0. enumerate makes the index of an element available while iterating a list. Checking remainder of division is done with the modulo operator.

lst = ['John', 21, 'Smith', 30, 'James', 25]

#Create list name to store the names
name = []
#Create list age to store the age
age = []

# use for loop to access every element of lst
# using enumerate(lst) let's us access the index of every element in the variable index see reference [0]
# The indexes of the list elements are as following:
# John: 0, 21: 1, Smith: 2, 30: 3, James: 4, 25: 5
for index,element in enumerate(lst):
    #Check if the index of an element can be divided by 2 without a remainder
    #This is true for the elements John, Smith and James:
    #0 / 2 = 0 remainder 0
    #2 / 2 = 1 remainder 0
    #4 / 2 = 2 remainder 0
    if index % 2 == 0:
       name.append(element)
    # If the division of the index of an element yields remainder, add the element to the list age
    # This is true for the elements 21, 30 and 25:
    # 1 / 2 = 0 remainder 1
    # 3 / 2 = 1 remainder 1
    # 5 / 2 = 2 remainder 1
    else:
        age.append(element)

print(name)
print(age)

References:

[0] https://docs.python.org/3/library/functions.html#enumerate
[1] https://docs.python.org/3.3/reference/expressions.html#binary-arithmetic-operations.

Osvald Laurits
  • 1,228
  • 2
  • 17
  • 32
0

A less convenient way is to use list indexing:

list = ['John', 21, 'Smith', 30, 'James', 25]
name=[list[0],list[2],list[4]]
print(name)
age=[list[1],list[3],list[5]]
print(age)
Kaleab Woldemariam
  • 2,567
  • 4
  • 22
  • 43