You can append the elements of one list to another with the "+=" operator. Note that the "+" operator creates a new list.
a = [1, 2, 3]
b = [10, 20]
a = a + b # Create a new list a+b and assign back to a.
print a
# [1, 2, 3, 10, 20]
# Equivalently:
a = [1, 2, 3]
b = [10, 20]
a += b
print a
# [1, 2, 3, 10, 20]
If you want to append the lists and keep them as lists, then try:
result = []
result.append(a)
result.append(b)
print result
# [[1, 2, 3], [10, 20]]
Answer from stackoverflowuser2010 on Stack OverflowVideos
You can append the elements of one list to another with the "+=" operator. Note that the "+" operator creates a new list.
a = [1, 2, 3]
b = [10, 20]
a = a + b # Create a new list a+b and assign back to a.
print a
# [1, 2, 3, 10, 20]
# Equivalently:
a = [1, 2, 3]
b = [10, 20]
a += b
print a
# [1, 2, 3, 10, 20]
If you want to append the lists and keep them as lists, then try:
result = []
result.append(a)
result.append(b)
print result
# [[1, 2, 3], [10, 20]]
Apart from + operator there's another way to do the same i.e. extend()
a = [1, 2, 3]
b = [10, 20]
a.append(b) # Output: [1, 2, 3, [10, 20]]
a.extend(b) # Output: [1, 2, 3, 10, 20]
You can use these 2 functions for manipulating a list as per your requirement.
I want to make a program which takes 3 inputs and prints them at last. But I don't know how to make it.
PSEUDO-CODE:
id = 0
ARRAY id_list
ARRAY name_list
WHILE id < 3 {
INPUT name
APPEND name TO ARRAY name_list
id += 1
APPEND id TO ARRAY id_list
WHILE id == 3 {
PRINT (ARRAY ELEMENT id_list[0] and ARRAY ELEMENT name_list[0])
PRINT (ARRAY ELEMENT id_list[0] and ARRAY ELEMENT name_list[1])
PRINT (ARRAY ELEMENT id_list[0] and ARRAY ELEMENT name_list[2])
BREAK
}
}
So if I have
x = [1, 2, 3] then x.append(4) will be [1, 2, 3, 4]
However, the code itself is unaffected by the code. So that's what I'm looking for right now. Possible how to write to an array in another file.
THANKS!
{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {} or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')