Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19k points)

I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list. Writing a + list I get errors. The compiler handles as integer, thus I cannot use append, or extend either. How would you do this?

2 Answers

0 votes
by (106k points)
  • For appending an integer to the beginning of the list in Python we can use the following method mentioned below. 
  • Now the reason why you were getting the error because you are using the variable name as the list that is not allowed in Python Python has some reserved keywords which can not be used as the variable name so instead of that, you should use the below-mentioned way:-

x = 5

abc_list = [1, 2, 3]

print([x] + abc_list)

       image

Another method that can be used to append an integer to the beginning of the list in Python is array.insert(index, value)this inserts an item at a given position. The first argument is the index of the element before which you are going to insert your element, so array.insert(0, x) inserts at the front of the list, and array.insert(len(array), x) is equivalent to array.append(x).

a=5

array = [2,3,4,5,6]

array.insert(0,a)

print(array) 

image

Wanna become an Expert in python? Come & join our Python Certification course

0 votes
by (1.9k points)

Concatenation makes it easy to create a new list starting with an integer

You can create a new list by concatenating an integer (wrapped in a list) with an existing list

my_integer = 5

my_list = [1, 2, 3, 4]

# Create a new list

new_list = [my_integer] + my_list

print(new_list) # Output: [5, 1, 2, 3, 4]

Using list comprehension

Or you can do this: Use list comprehension:

my_integer = 5

my_list = [1, 2, 3, 4]

# Create a new list

new_list = [my_integer] + [item of item in my_list]

print(new_list ) # Output: [5, 1, 2, 3, 4]

Using 'append'

Using 'append', you can start with an empty list and append integers and elements to an existing list:

my_integer = 5

my_list = [1, 2, 3, 4]

# Start with an empty list

new_list = []

new_list.append(my_integer) # Add an integer

# Expand in the original list

new_list.extend (my_list)

print(new_list) # Output: [5, 1, 2, 3, 4]

Related questions

+1 vote
2 answers
0 votes
4 answers
0 votes
4 answers
asked Apr 6, 2021 in Python by laddulakshana (16.4k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...